问题描述
世界上如何在中使用嵌套路由,特别是版本4.x的?以下版本在以前的版本中运行良好...
How in the world does one use nested routes in react-router, specifically, version 4.x? The following worked well in previous versions...
<Route path='/stuff' component={Stuff}>
<Route path='/stuff/a' component={StuffA} />
</Route>
升级到4.x会发出以下警告......
Upgrading to 4.x throws the following warning...
这里到底发生了什么?我花了几个小时的时间来搜索,无法成功地使嵌套路由正常工作。如何使用< Route>
组件将其路由嵌套在react-router v4中?我的简单示例如何转换为嵌套路由的v4.x API合规性?
What in the heck is going on here? I've scoured the docs for hours and can not successfully get nested routes working. How does one use <Route>
components to nest their routes in react-router v4? How does my simplistic example translate to v4.x API compliance to nest a route?
推荐答案
忘掉你对React Router<的了解; V4。您通过字面嵌套< Routes>
来嵌套路线。查看。具体来说,请查看主题组件。您不会预先声明路线,而是在组件渲染时动态声明。
Forget what you know about React Router < v4. You nest routes by literally nesting <Routes>
. Check this example. Specifically check out the Topics component. You don't declare your routes up front but instead dynamically when a component renders.
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const BasicExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
{/* NESTED ROUTES */}
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
export default BasicExample
这篇关于为什么我不能在react-router 4.x中嵌套Route组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!