react-router v4嵌套路由问题 [英] react-router v4 nesting routing issue

查看:106
本文介绍了react-router v4嵌套路由问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下情况:

<Wrapper>
   <Container>
      <Route exact path="/" component={UserListing} />
      <Route path="/user/:id" component={UserDetails} />
      <Route exact path="(/|/user/\d+)" component={StaticComponent} />
   </Container>

   <Route path="/create-account" component={CreateAccount}/>
</Wrapper>

Okey,所以我的情况很简单:我不想要 Container 如果路径不等于// user /:id
因此,如果路径/ create-account Wrapper CreateAccount 小孩应该出现,没有容器

Okey, so my case is simple: I don't want the Container component to render if path does not equal to "/" or "/user/:id". So if path is "/create-account" only Wrapper with CreateAccount as child should appear, without Container.

寻找帮助。谢谢

推荐答案

您可以编写一个自定义组件来决定是否渲染容器,如

You can write a custom component that decides whether or not to render Container like

const RouterRenderer = ({ location, children }) => {
    if(location && location.state && location.state.noMatch) {
        return null;
    }
    return children;
}

还有一个子组件告诉这个容器没有匹配像

And a sub component which tells this container that nothing matched like

const NoMatch = () => {
    return <Redirect to={{state: {noMatch: true}}} />
}
export default withRouter(NoMatch);

现在你可以使用它们

<Wrapper>
   <RouterRenderer>
       <Container>
          <Switch>
              <Route exact path="/" component={UserListing} />
              <Route path="/user/:id" component={UserDetails} />
              <Route exact path="(/|/user/\d+)" component={StaticComponent} />
              <NoMatch />
          </Switch>
       </Container>
   </RouterRenderer>
   <Route path="/create-account" component={CreateAccount}/>
</Wrapper>




PS 请注意,使用它很重要当您使用 NoMatch 组件时,切换,因为您只想在没有其他
路由匹配时才呈现它。你也可以用HOC的
形式编写RouteRenderer函数而不是函数组件。

P.S. Note that its important to use Switch when you are using NoMatch component since you want to render it only when no other route matched. Also you can write RouteRenderer function in the form of an HOC instead of a functional component.

这篇关于react-router v4嵌套路由问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆