gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:34:06 25 4
gpt4 key购买 nike

我已将应用程序中的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com