继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

React-Routerv4 踩坑以及填坑

东方既白233
关注TA
已关注
手记 44
粉丝 38
获赞 153

跟着很早前的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)
    }   
}


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP