【问题标题】:react-router v4 nesting routing issuereact-router v4嵌套路由问题
【发布时间】:2019-01-07 02:32:10
【问题描述】:

我有以下情况:

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

好的,所以我的情况很简单:如果路径不等于 "/""/user/:id",我不希望 Container 组件呈现。 因此,如果路径是"/create-account",则只有WrapperCreateAccount 作为孩子应该出现,没有Container

寻求帮助。谢谢

【问题讨论】:

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


    【解决方案1】:

    你可以编写一个自定义组件来决定是否像容器一样渲染

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

    还有一个子组件告诉这个容器没有匹配的东西

    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>
    

    P.S. 请注意,在使用 NoMatch 组件时使用 Switch 很重要,因为您只想在没有其他组件时才渲染它 路线匹配。您也可以编写 RouteRenderer 函数的形式 使用 HOC 而不是功能组件。

    【讨论】:

    • 只有Route可以解决我的问题吗?如果没有这些道具处理和Redirect?
    • @Patrickkx,上述案例以一般方式处理您的用例,也可以在没有上述方法的情况下处理它,但这需要您在 Container 和将其渲染为路线
    猜你喜欢
    • 2017-08-28
    • 2017-06-25
    • 2017-11-11
    • 1970-01-01
    • 2017-10-05
    • 2017-07-04
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多