【问题标题】:How to conditionally render wrapping components in React Router 4/5如何在 React Router 4/5 中有条件地渲染包装组件
【发布时间】:2019-05-02 23:37:45
【问题描述】:

我正在将一个应用程序从 react-router 版本 3 迁移到 5,并且在试图找出解决以下问题的最佳方法时有点卡住了。

我有一些使用包装组件的路由。

在 routerv3 中我可以做类似的事情

const Container = props => 
  <div>
    <header>container1</header>
    { props.children } 
  </div>

const Container2 = props => 
  <div>
    <header>container2</header>
    { props.children } 
  </div>

这些容器还有其他功能

<Route component={Container}>
  <Route path='/container1' component={Page1} />
</Route>

<Route component={Container2}>
  <Route path='/container2' component={Page1} />
</Route>

当导航到/container1 时,它会渲染Page1 组件并用Container1 包裹它,然后在/container2 上它会渲染Page1Container2 包裹它。

但是,当移动到路由器 v4+ 时,所有匹配的路由都会被渲染,所以发生的情况是,例如在 /container2 上,结果是

<div>
  <header>container1</header>
</div>
<div>
  <header>container2</header> 
  <Page1 />
</div>

有谁知道编写这些“包装组件”的方法,以便仅在路由匹配时才呈现它们?或者如果这不是 react-router 4/5 的工作方式,也许是做这种事情的更好方法。

这是我试图解决这个问题的堆栈闪电的链接

https://stackblitz.com/edit/react-jvsdsn?file=index.js

【问题讨论】:

    标签: javascript reactjs react-router react-router-v4 react-router-dom


    【解决方案1】:

    你可以这样做

    <Route
      path="/container1"
      render={(routeProps) => (
        <Container>
          <Page1 {...routeProps} />
        </Container>
      )}
    />
    <Route
      path="/container2"
      render={(routeProps) => (
        <Container2>
          <Page1 {...routeProps} />
        </Container2>
      )}
    />
    

    【讨论】:

    • 这并不能解决问题,因为您仍在定义容器上方的实际路径。我想说容器包装了多条路径。
    • 容器是一个组件。如果您需要一个通用的位置来放置容器,而不是将所有路由渲染包装在相应的容器内,您可能必须为路由创建一个前缀。
    • 所以你说我应该做类似```
      container1 content
      .... ``` 这样做的问题是它改变 url 只是为了做一些我可以在 RR3 中做的事情
    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    相关资源
    最近更新 更多