React 应用很少不用react-router这个包的。marknoteapp.com之前一直用v3,看到v4出来后一直心痒。最近,抱着 用新不用旧 的理念,手贱升了一下级。这一升级,差不多2天功夫花掉啦。
和 Angular 那改朝换代般的升级相比,React技术栈一直以其稳定的 API 而备受好评。不过,这次 react-router 从v3到v4的升级,简直是砸 React 的好名声的。
如果你以为这个升级只是在 package.json 中简单的改一下版本号就好了,那你就大错特错了。我相信,你改完版本号之后,会像我当初一样面对成堆的问题而惊奇不已。
事实上,不少开发者对v4的的变化感到惊诧,比如下面的这位就抱怨v3升v4花了10天。
总之,v3到v4不是一件几分钟就可以搞定的事。一个中型的项目,花2-3天在升级上很正常。
重要的事情说三遍:升级之前先备份!升级之前先备份!!升级之前先备份!!!
备份完之后,就和我一起来踩坑吧!
react router v4 是对v3的重写。现在分为三个包:
对于一般的web应用,直接引入第二个包即可,安装之前先删除老版本react-router:
npm uninstall react-router --savenpm install --save react-router-dom
或者你像我一样,更亲睐yarn的话:
yarn remove react-routeryarn add react-router-dom
引入完之后,要做的第一件事就是将所有原先引入react-router的地方都换成react-router-dom。
// 原先import { Route, Redirect } from 'react-router';// 现在import { Route, Redirect } from 'react-router-dom';
在V3中,一般使用,只是在其history属性中指定是哪种实现: hashHistory或者browserHistory之类的。
// v3import { Router, hashHistory } from 'react-router';const MyApp = () => ( <Router history={hashHistory}> ... </Router>);
而在v4中,你需要直接用具体的实现,比如HashRouter或者BrowserRouter:
// v4import { HashRouter } from 'react-router-dom';const MyApp = () => ( <HashRouter> ... </HashRouter>);
如果你像我一样,也用了redux的话,那么恭喜你,你还得用react-router-redux。
而且,这个包的正式版4.x不支持react-router v4。你需要用 alpha 版 的react-router-redux。在package.json 里加入react-router-redux~5.0.0或者用yarn:
yarn add react-router-redux@5.0.0
虽然我用的是alpha 6,貌似也没啥毛病。
而且,对于redux应用,你不可以用BrowserRouter,或者HashRouter,而应该使用ConnectedRouter。
比如,我的代码:
import { Route } from 'react-router-dom';import history from 'history/createBrowserHistory';import { ConnectedRouter, routerReducer, routerMiddleware } from 'react-router-redux';import App from './components/App';ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history()}> <Route path="/" component={App} /> </ConnectedRouter> </Provider>, document.getElementById('root'));
在V3中,嵌套Route和Index Route的使用是很常见的。比如marknoteapp.com中,博客部分的路由定义如下:
<Route path="/blog/:bloggerId" component={BlogLayout}> <IndexRoute component={BlogList}/> <Route path="/blog/:bloggerId/settings" component={BlogConfig}/> <Route path="/blog/:bloggerId/about" component={BlogAbout}/> <Route path="/blog/:bloggerId/dashboard" component={BlogDashboard}/> <Route path="/blog/:bloggerId/:postId" component={BlogPost}/></Route>
这样/blog/123 会触发BlogLayout,和BlogList,而/blog/123/456则会触发BlogLayout和BlogPos。很方便。
在 v4 中 IndexRoute没了,然后不允许Route嵌套。
要实现类似的功能,需要两步:
<Switch> <Route path="/blog/:bloggerId" component={BlogLayout} /></Switch>
<div className='content' id="blog-content"> <Switch> <Route exact path="/blog/:bloggerId/settings" component={BlogConfig} /> <Route exact path="/blog/:bloggerId/about" component={BlogAbout} /> <Route exact path="/blog/:bloggerId/dashboard" component={BlogDashboard} /> <Route exact path="/blog/:bloggerId/:postId" component={BlogPost} /> <Route exact path="/blog/:bloggerId" component={BlogList} /> </Switch></div>
这里有几点需要注意:
比如在我的代码中, 在BlogLayout中,我可以 match.url 来代替“/blog/:bloggerId”,代码如下:
<div className='content' id="blog-content"> <Switch> <Route exact path={"${match.url}/settings"}} component={BlogConfig} /> <Route exact path={"${match.url}/about"} component={BlogAbout} /> <Route exact path={"${match.url}/dashboard"} component={BlogDashboard} /> <Route exact path={"${match.url}/:postId"} component={BlogPost} /> <Route exact path={"${match.url}}component={BlogList} /> </Switch></div>
在 v3 中,你可以从params这个属性中取到URL 中传递过来的参数。比如我在 BlogLayout中获取bloggerID,v3的代码如下:
//v3const bloggerId = this.props.params.bloggerId;
这个属性在v4中不再被自动注入了,需要从match属性中获取。代码如下:
//v4const bloggerId = this.props.match.params.bloggerId;
这里还有一个小小的差异。在v3中,参数会自动解码,而在v4中不会。所以如果你的URL参数中有特殊字符的话,你可能需要自己调decodeURI之类的方法解码。
在v3中,我可以使用使用 Route的 onEnter, onUpdate和 onLeave事件来做一些事情。
比如,我可以在onUpdate中触发google analytics来跟踪用户行为:
//v3<Router history={browserHistory} onUpdate={doLogPageView} >
这里doLogPageView实现如下:
function doLogPageView(){ const sUrl = window.location.pathname + window.location.search; ReactGA.set({ page: sUrl }); ReactGA.pageview(sUrl);}
在v4中,Route的事件没了。我查了很多资料,貌似有两种解决办法:
我用的后一种方法,代码如下:
import { withRouter } from 'react-router-dom';import ReactGA from 'react-ga';class App extends Component { componentWillMount() { this.setState( { height: window.innerHeight, sidebarOpen: false, docked: true, } ); this.onSetSidebarOpen = this.onSetSidebarOpen.bind(this); this.props.history.listen((location, action) => { const url = location.pathname + location.search + location.hash; ReactGA.set({ page: url }); ReactGA.pageview(url); console.log(`current URL:${url}`); }); }}export default withRouter(App);
简单的说,react-router v4 简直不像是v3的升级,而更像一次天马行空的重写。其理念是完全不一样的。v3 更像是AOP (面向切面编程)的样子:路由全局配置,可以通过 事件进行一些共通的处理;v4 用react-router 团队的话说是 real component,可以嵌入任何组件中。
据说 facebook 的react 团队对 v3之前的react-router 一直没有好感,而v4之后则颇多溢美之词。
但是客观的讲,从v3升级到 v4遇到的问题还是比较多的。尤其是官方居然没有一个全面的指南。虽然在 这里 有一个文档,但是很多实际升级时会遇到的问题都没有涉及。
你的项目用的v3 还是 v4?需要升级吗?升级遇到什么问题,可以在下面留言,一起探讨。
感谢作者marknote授权发布。
作者简介: marknote,个人开发者,专注iOS和web相关技术,喜好尝试新技术,热爱分享。 个人邮箱:marknote@aliyun.com,点击查看: 博客地址,简书个人主页。
联系客服