-
Notifications
You must be signed in to change notification settings - Fork 17
项目实践:从react-router v3迁移到v4 #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
感觉v2/v3 相当于静态路由,必须在一个配置文件中,作为entry来打包,v4 相当于动态路由,可以和JSX随意结合,比较好。 |
用过express router的同学应该会对配置路由比较熟悉。react-router v4就是遵循组件化的思想,对于react入门的新手而言会相对容易理解些。个人认为以后的趋势还是会慢慢迁移到v4的。 @rongchanghai |
这里补充点:state.location中在V4会缺少个action字段,这个action的值有'PUSH','REPLACE','POP'三种。详细看这个commit: YutHelloWorld/vortex-react@b9a354e |
将路由写在组件里面真的好嘛,有什么优势?个人觉得反而将将路由配置写在一个文件里,整个应用的页面架构一目了然,更清晰。 |
写在组件里也能够看到整个应用的页面结构啊,例如: function Layout() {
return (
<div className="layout-c">
<Navbar />
<Switch>
<Route exact path="/" component={OrderList} />
<Route exact path="/admin" component={ProductList} />
<Route exact path="/competition" component={AsyncCst} />
<Route path="/admin/add" component={AsyncAdd} />
<Route
path="/admin/detail/:goodsType/:goodsId"
component={ProductDetail}
/>
<Route path="/admin/:type" component={AdminType} />
<Route path="/detail/:orderId" component={OrderDetailContent} />
<Route path="/competition/orderPool" component={CmpOrderList} />
<Route render={() => <div className="layout-content" />} />
</Switch>
<Footer />
</div>
);
} |
@YutHelloWorld ,在管理后台中想要根据不同的角色从后台返回的菜单,动态生成侧边栏菜单该如何配置呢?望指教。 |
谢谢,在写V2的时候遇到问题搜到这个了,不过还是很不错,可以考虑自己玩耍下V4 |
在v3中 我可以将相同的layout布局放在一个顶层组件中,然后通过this.props.children,内部组件加载可以通过content得到布局样式。但是v4让我很不适应。可能不论是vue目前还是ng依然是路由集中配置。 |
Uh oh!
There was an error while loading. Please reload this page.
前言
迁移步骤
React-Router和Redux同步
1. 替换依赖包
v3我们引入的是
react-router
包,在v4我们只引入react-router-dom
这个包。安装react-router-dom
时会同时安装history
。package.json
2. 改写对browserHistory的创建和当前location的获取
location.js
==>
这里替换的是history,和当前location的获取方法。在v3,browserHistory存在于
react-router
中,而v4把history抽离了出来,提供了createBrowserHistory
,createHashHistory
,createMemoryHistory
三种创建history的方法。v4中创建的history导出,在后面会需要用到。3. 对history绑定监听事件,把location的改变同步到Redux的store中
createStore
updateLocation
用来把location的更新同步到store中。一切似乎都很顺利,接着第一个坑来了
根据
history
API提供的修改
createStore.js
==>
接着修改
app.js
==>
我们到浏览器中查看,发现URL变化并没有触发
updateLocation(store)
,state并没有变化。What a f**k!
问题出在
BrowserRouter
在创建的时候在内部已经引入了一个history
,updateLocation(store)
应该监听的是内部的这个history
。这里贴下BrowserRouter.js的代码于是,我们放弃使用
BrowserRouter
,而使用Router
。修改
app.js
==>
这样,这个坑算是填上了。也就完成了history和store之间的同步。
重写路由
routes/index.js
==>
这里路由的定义方式由PlainRoute Object改写成了组件嵌套形式,在
PageLayout.js
中插入<Routes />
。代码分割
Counter/index.js
首先,新增
AsyncComponent.js
接着,改写
Counter/index.js
==>
琐碎API的替换
==>
==>
总结
这里可以看出,使用v4替换v3,对于大型项目并不是一件轻松的事情,有许多小坑要踩,这就是社区很多项目仍然使用v2/v3的原因。笔者认为,v4更符合React的组件思想,于是做了一个实践。最后欢迎指正拍砖,捂脸求star 🤣 。
参考
The text was updated successfully, but these errors were encountered: