react-router 4.0踩到的坑

接手的项目需要二次开发,项目是使用的react+react-router4.0+antd+redux来开发的,由于之前用的是react-router2.0,react-router2.0和4.0之间变化还是挺多的,在这里记录一下踩到遇到的问题

1.dom组件不再在react-router中引入,而是在react-router-dom中引入

2.不再使用<Router history={}>来定义history属性,4.0加入了BroswerRouter和HashRouter组件,引入时可以import {BrowserRouter as Router} from 'react-router-dom' 来引入

3.<Router>组件下只能有一个单独的节点,类似render return下,只能有一个父节点,并且Router下的单一父节点下,现在可以放入其他组件,不一定是Route组件了。

4.<Route>组件增加了exact属性,添加了这个属性之后,如这个组件path='/one',则不会再匹配url='/one/two'的路由地址

5.<Route>下增加子路由会报错,现在<Route>下不能添加子路由,如果想要添加子路由,则到该路由下匹配的组件中添加<Route>

6.react-router中不再有BrowserHistory,要在js中进行路由跳转,不依赖Link,需要使用contextTypes越级传递router,使用router下的方法在js中进行路由跳转,并且在新版react中,PropTypes不再存在于React下,需要单独从prop-types中引入,具体实现方法如下

import React,{Component} from 'react'
import PropTypes from 'prop-types'

class Example from Component {
       constructor(props){
                super(props)
                this.clickHandle = this.clickHandle.bind(this)
        }    
        clickHandle(){
            this.context.router.history.push(url)
        }    
        render(){
                return(
                    <div>
                        <button onClick={this.clickHandle}></button>
                    </div>
            }
}

Example.contextTypes = {
    router:PropTypes.object
}

export default Example

暂时遇到的问题是这些,后续遇到问题会再继续补充

posted @ 2018-01-25 11:48  金刚航母  阅读(194)  评论(0编辑  收藏  举报