问题描述
我在 Web 和 SO 上搜索了很多,在 reactiflux 聊天中询问,但没有找到一种干净且非黑客外观的方式来根据路由/路径渲染某些组件.
I searched a lot on the Web and SO, asked in reactiflux chat, but didn't found a clean and non-hack-looking way of rendering some component depending of route/path.
假设我有 <Header/>
,它应该显示在某些页面上,而应该隐藏在其他页面上.
Let's say I have the <Header />
which should be shown on some pages and should be hidden on other ones.
当然我可以在 Header 组件中使用这个字符串
For sure I can use this string in Header component
if (props.location.pathname.indexOf('/pageWithoutAHeader') > -1) return null
那完全没问题,如果 /pageWithoutAHeader
是唯一的.如果我需要 5 个页面的相同功能,它会变成这样:
That's totally fine, if /pageWithoutAHeader
is the unique. If I need same functionality for 5 pages it become this:
if (props.location.pathname.indexOf('/pageWithoutAHeader1') > -1) return null
if (props.location.pathname.indexOf('/pageWithoutAHeader2') > -1) return null
if (props.location.pathname.indexOf('/pageWithoutAHeader3') > -1) return null
是的,我可以将路由存储在数组中并编写一个循环,这样代码可重用性更高.但这是处理这个用例的最好和最优雅的方式吗?
Yes, I can store routes in the array and write a loop, which will be more code-reusable. But is it a best and the most elegant way to handle this use case?
我相信它甚至可能有问题,例如,如果我不为带有路由 /xyz
的页面渲染标题,并且我有带有 UUID 的路由,例如 /projects/:id
和 id=xyzfoo
,所以 /projects/xyzfoo
不会显示标题,但它应该显示.
I believe that it can be even buggy, for example if I don't render header for a page with a route /xyz
and I have routes with UUIDs, like /projects/:id
, and id=xyzfoo
, so /projects/xyzfoo
won't show a header but it should.
推荐答案
您可以先列出所有没有标题的路由,然后在附加开关中将其他路由分组:
You can list all routes without a header first and group others in additional switch:
...
<Switch>
<Route path="/noheader1" ... />
<Route path="/noheader2" ... />
<Route path="/noheader3" ... />
<Route component={HeaderRoutes} />
</Switch>
...
HeaderRoutes = props => (
<React.Fragment>
<Header/>
<Switch>
<Route path="/withheader1" ... />
<Route path="/withheader2" ... />
<Route path="/withheader3" ... />
</Switch>
</React.Fragment>
)
来自文档:
没有路径的路由总是匹配的.
不幸的是,此解决方案可能存在未找到"页面的问题.它应该放置在 HeaderRoutes
的末尾,并且将使用 Header
呈现.
Unfortunately this solution might have a problem with "not found" page. It should be placed at the end of the HeaderRoutes
and will be rendered with a Header
.
Dhara 的解决方案没有这样的问题.但如果 React Router 内部结构发生变化,它可能不适用于 Switch
:
Dhara's solution doesn't have such problem. But it might not work well with Switch
if React Router internals change:
的所有子元素都应该是
或
元素.只会呈现与当前位置匹配的第一个孩子.
Route
上的 HOC 不是 Route
本身.但它应该可以正常工作,因为当前的代码库实际上期望任何 React.Element
与 和
具有相同的 props 语义> 有.
HOC over Route
is not a Route
itself. But it should work fine because current codebase in fact expects any React.Element
with the same props semantics as <Route>
and <Redirect>
have.
这篇关于根据路由处理条件组件渲染的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!