在 react-router v4 中嵌套路由
Nesting Routes in 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 在最新版本中不可用,并且 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>
)
}
嵌套路由在版本 react-router 4.x 中不可用。这是关于如何在 v4.x.
中为嵌套路由 secnarios 编码的 basic example straight from react-router documentation
也看看这个问题
我已经在我的应用程序中将 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 在最新版本中不可用,并且 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>
)
}
嵌套路由在版本 react-router 4.x 中不可用。这是关于如何在 v4.x.
中为嵌套路由 secnarios 编码的 basic example straight from react-router documentation也看看这个问题