将路由嵌套在react-router v4中

时间:2017-06-09 08:25:34

标签: reactjs react-router url-routing react-router-v4

我已在我的应用程序中将react路由器升级到版本4。但现在我收到了错误

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

此路由有什么问题?

import {
    Switch,
    BrowserRouter as Router,
    Route, IndexRoute, Redirect,
    browserHistory
} from 'react-router-dom'   

render((
    <Router history={ browserHistory }>
        <Switch>
            <Route path='/' component={ Main }>
                <IndexRoute component={ Search } />
                <Route path='cars/:id' component={ Cars } />
                <Route path='vegetables/:id' component={ Vegetables } />
            </Route>
            <Redirect from='*' to='/' />
        </Switch>
    </Router>
), document.getElementById('main'))

2 个答案:

答案 0 :(得分:9)

IndexRoute和browserHistory在最新版本中不可用,路由不接受带有v4的子路由,而是可以在组件中指定路由本身

import {
    Switch,
    BrowserRouter as Router,
    Route,  Redirect
} from 'react-router-dom'   

render((
    <Router>
        <Switch>
            <Route exact path='/' component={ Main }/>

            <Redirect from='*' to='/' />
        </Switch>
    </Router>
), document.getElementById('main'))

然后在主要组件

render() {
     const {match} = this.props;
     return (
        <div>
           {/* other things*/}
           <Route exact path="/" component={ Search } />
           <Route path={`${match.path}cars/:id`} component={ Cars } />
         </div>
    )

}

同样在汽车组件中

你会有

render() {
     const {match} = this.props;
     return (
        <div>
           {/* other things*/}
           <Route path={`${match.path}/vegetables/:id`} component={ Vegetables } />
        </div>
    )

}

答案 1 :(得分:0)

版本react-router 4.x无法使用嵌套路由。以下是来自react-router basic exampledocumentation关于如何在v4.x中嵌套路由secnarios的代码。

同时查看此问题Why can I not nest Route components in react-router 4.x?