【问题标题】:Nesting Routes in react-router v4在 react-router v4 中嵌套路由
【发布时间】:2017-11-11 04:19:44
【问题描述】:

我已在我的应用程序中将反应路由器升级到版本 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'))

【问题讨论】:

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


    【解决方案1】:

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

    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>
        )
    
    }
    

    【讨论】:

    • 在 JSX 中不再允许使用裸 JS 模板文字。因此,您需要使用以下内容:${match.path}/vegetables/:id} ... />
    • 在使用嵌套路由时要小心使用精确的位置。 Exact 将仅匹配该确切路径,例如,exact="/" 与 /posts/:id 不匹配 - 这让我作为一个新用户在尝试进行嵌套布局时有点绊倒。
    【解决方案2】:

    react-router 4.x 版本不提供嵌套路由。这是直接来自 react-router documentationbasic example,关于如何在 v4.x 中为嵌套路由 secnarios 编写代码。

    也看看这个问题Why can I not nest Route components in react-router 4.x?

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 2017-06-25
      • 2019-01-07
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2017-08-16
      相关资源
      最近更新 更多