react-router v4 nesting routing issue

ⅰ亾dé卋堺 提交于 2019-12-06 16:47:06

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);

Now you can use them like

<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>

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!