reactjs - 在react-router v4中嵌套路由

标签 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'))

最佳答案

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

}

关于reactjs - 在react-router v4中嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44452858/

相关文章:

javascript - 在 usestate hook 中更新状态后,React 不会更改状态(以自定义函数形式)

javascript - inner函数如何获取 'dispatch'参数?

Elasticsearch:从/到/elastic 更改根 url

javascript - React Router requireAuth 不重定向

javascript - 在routes.js 中意外导入 token

asp.net - 如何在 IIS Express 下启用区分大小写?

c# - ActionLink、Html.BeginForm、Url.Content如何匹配正确的Route

javascript - Admin-On-REST 自定义 REST 客户端编译失败

javascript - 根据视口(viewport)高度动态添加内容到引用的 React 子级

javascript - React-router v4 在页面更改时调度 redux 操作