react中路由配置,更改react router 3的写法,转成react router4.0

class App extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state = {
            initDone: false
        }
    }
    render() {
        return (
            <div>
                {
                    this.state.initDone
                    ? this.props.children
                    : <div>正在加载...</div>
                }
            </div>
        )
    }

上面是一个app总的页面

lass RouterMap extends React.Component {
    render() {
        return (
            <Router history={this.props.history}>
                <Route path='/' component={App}>
                    <IndexRoute component={Home}/>
                    <Route path='/city' component={City}/>
                    <Route path='/Login(/:router)' component={Login}/>
                    <Route path='/User' component={User}/>
                    <Route path='/search/:category(/:keyword)' component={Search}/>
                    <Route path='/detail/:id' component={Detail}/>
                    <Route path='*' component={NotFound}/>
                </Route>
            </Router>
        )
    }
}

这是REACT router 的配置,不过是react-route3 的写法,我现在想改成router 4.0的写法,该怎么写

class RouterMap extends React.Component {
    render() {
        return (
            <BrowserRouter history={this.props.history}>

                      <Switch>
                            <Route exact path='/' component={Login}/>
                            <Route path='/login' component={Login}/>
                            <Route path='/home' component={Home}/>
                            <Route component={NotFound}/>
                      </Switch>

            </BrowserRouter>
        )
    }
}

这是我写的,为了不报错删去了app那个组件,现在不知道怎么吧app组件写进去。有没有大神教一下

阅读 2.6k
2 个回答

其实如果不是很明确的话,不太推荐升级到4,变化太大,但是好处不显而易见。

你这里的话最重要是转换观念,4里面所有的路由都是一个react组件。

其实你这里的RouterMap就是你的App组件。

简单来说,在3里面,router和layout是分开来的。 而在4里,router和layout是结合在一起的。所以你这里只需要把原本写在App里的逻辑同样的写在RouterMap上就行。甚至把RouterMap直接换个名字叫App都可以。

可以参考doc

结合redux的一个代码,可以参考下,外层有个ConnectedRouter组件,传递match属性:


class Root extends React.PureComponent<RootProps, any> {
  render() {
    return (
      <Provider store={this.props.store}>
        <ConnectedRouter history={this.props.history}>
          <Route path={getPathPrefix()} component={({match}) => <App roleCode={this.props.roleCode} match={match}/>}/>
        </ConnectedRouter>
      </Provider>
    )
  }
}

子组件比如:

<div className="page-content">
        <Route path={`${match.url}/page1`} component={PageA}/>
        <Route path={`${match.url}/page2`} component={PageB}/>
</div>

如果还要按需加载,还需要加点代码。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题