React Router v4 嵌套在嵌套组件中
React Router v4 Nested within Nested components
我们就拿这个
{/* NESTED ROUTES */}
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
嵌套路由工作正常。但是,如何在嵌套路由中嵌套路由?例如:
path={`${match.url}/:topicId/edit`} component={EditTopic}
是否有 good/bad 嵌套多少层的练习指南?任何 tips/guidance 不胜感激!
而不是使用 match.url
,您需要使用 match.path
来构建嵌套路由。根据match
documentation
path - (string) The path pattern used to match. Useful for building nested <Route>s
url - (string) The matched portion of the URL. Useful for building nested <Link>s
how can I nest a Route within a nested route?
React Router v4 鼓励您像考虑任何其他组件一样考虑 Route
。它可以帮助您根据 url.
中发生的情况构建界面
所以 - 您不应该对嵌套 Route
或在组件树深处使用它们来修改界面以响应 url.
感到奇怪
在您的示例中,您可以在 Topic
组件或作为 render
prop 传递的函数中进一步嵌套 Route
。
Is there a good/bad practice guide for how many levels you would nest?
这是一个很好的问题。像许多其他事物一样,它归结为品味。在六个月的时间内让您的代码易于他人和您自己理解。
在某些情况下,采用老式方法并将所有路由保留在一个组件中可能是最简单的方法。在其他情况下,使用四层嵌套会更好。
在我的团队中,我们采用了 v4 并使用了多层嵌套。一路上我们进行了很多对话,以确保每个人都清楚方法。
注意: 如果您将深度嵌套与例如redux connect
或 react PureComponent
,请注意,这些可能会阻止对嵌套 Route
的位置更新。当您的 Route
不响应 url 中的更改时,您就会知道发生了这种情况。使用 withRouter
来解决这个问题。
我们就拿这个
{/* NESTED ROUTES */}
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
嵌套路由工作正常。但是,如何在嵌套路由中嵌套路由?例如:
path={`${match.url}/:topicId/edit`} component={EditTopic}
是否有 good/bad 嵌套多少层的练习指南?任何 tips/guidance 不胜感激!
而不是使用 match.url
,您需要使用 match.path
来构建嵌套路由。根据match
documentation
path - (string) The path pattern used to match. Useful for building nested
<Route>s
url - (string) The matched portion of the URL. Useful for building nested
<Link>s
how can I nest a Route within a nested route?
React Router v4 鼓励您像考虑任何其他组件一样考虑 Route
。它可以帮助您根据 url.
所以 - 您不应该对嵌套 Route
或在组件树深处使用它们来修改界面以响应 url.
在您的示例中,您可以在 Topic
组件或作为 render
prop 传递的函数中进一步嵌套 Route
。
Is there a good/bad practice guide for how many levels you would nest?
这是一个很好的问题。像许多其他事物一样,它归结为品味。在六个月的时间内让您的代码易于他人和您自己理解。
在某些情况下,采用老式方法并将所有路由保留在一个组件中可能是最简单的方法。在其他情况下,使用四层嵌套会更好。
在我的团队中,我们采用了 v4 并使用了多层嵌套。一路上我们进行了很多对话,以确保每个人都清楚方法。
注意: 如果您将深度嵌套与例如redux connect
或 react PureComponent
,请注意,这些可能会阻止对嵌套 Route
的位置更新。当您的 Route
不响应 url 中的更改时,您就会知道发生了这种情况。使用 withRouter
来解决这个问题。