跟着很早前的react学习视频打算过一边,由于视频使用的是react-router3 而我用的是creat-react-app脚手架使用的是最新的react-router v4,所以发现踩了不少坑。这里对于比较明显的坑进行总结。
1. route4中禁止Route 路由元的嵌套,在router3中,Route是可以互相嵌套的,相当于父级路由跟子路由。
在router3中这种写法是可以的,也是规范,这种跟vue的vuerouter也很像,就是通过路由去映射组件
<Router>
<Route exact component={home} path='/' >
<Route component={container} path='/container' />
</Route&rt;
</Router>
但是这种写法在router4就不行了,react16跟router4的理念:
一切皆组件,就连router也是以组件的形式进行嵌套~而且在Route的最外层要包裹一层非路由组件,
Route只能同级,不能嵌套,嵌套只能嵌套在父组件为react非路由组件下。
<Router>
<Home >
<Route component={container} path='/nav' />
<Route component={container} path='/container' />
</Home >
</Router >2.react-router v4实现编程式导航与以往的区别
route4中禁止从react-router-dom 直接引入history,这个接口被封闭了,直接引入的话,会受到报错提示。在router3中,history是可以直接从react-router-dom引入的
但是很神奇的事,在另外一个地方,react-router暴露了这个createBrowserHistory...
所以自己去引入实例化一个吧。
---history.js
import createHistory from 'history/createBrowserHistory';
export default createHistory();
之后在你要在Router外层引入history这个属性
---router/router.js
import history from '../router/history'
import { Router, Route, Switch } from 'react-router-dom'
<Router history={history} >
<Home >
<Route component={container} path='/nav' />
<Route component={container} path='/container' />
</Home >
</Router >
然后在你需要使用编程式导航的地方,直接引入这个实例
import React from 'react'
import history from './../../router/history'
class List extends React.PureComponent {
render() {
const arr=[1,2,3]
return (
<ul>
{
arr.map((item,index)=>{
return <li key={index} onClick={this.clickHandler.bind(this,item)}>{item}</li&lgt;
})
}
</ul>
);
}
clickHandler(value){
history.push('/detail/'+value)
}
}點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦