【问题标题】:React Router 4 Nested Routes not renderingReact Router 4嵌套路由未呈现
【发布时间】:2017-11-15 12:58:47
【问题描述】:

我正在尝试在我的一个组件中进行嵌套路由。

这是父组件:

const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <Switch>
        <Route exact path="/" component={Landing} />
        <Route path="/contribute" component={Contribute} />
      </Switch>
    </Provider>
  </BrowserRouter>
);

这是子组件:

const Landing = () => (
  <div>
    <SearchBar />
    <section className="results-sctn">
      <Route exact path="/" component={ArtistList} />
      <Route path="/test" component={Test} />
    </section>
  </div>
);

ArtistList/ 路由上呈现良好,但 /test 呈现完全空白的页面。知道为什么会这样吗?

【问题讨论】:

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


    【解决方案1】:

    发生这种行为是因为在父路由中提到了 exact 属性

    <Route exact path="/" component={Landing} />
    

    所以发生的情况是 react-router 看到要匹配的路径/test,然后尝试从顶层开始匹配它。它看到两条路线,一条是exactly /,另一条是/contribute。它们都不匹配所需的路径,因此您会看到一个空白页

    你需要写

    <Route path="/" component={Landing} />
    

    因此,当您执行此操作时,它会看到与 /test 部分匹配的 /,然后会尝试在它会找到的 landing 组件中找到匹配的路由。

    还要更改父路由的顺序,因为Switch 呈现第一个匹配项,而//test 的部分匹配项,所以/contribute 将不起作用

    您的最终代码如下所示

    const App = () => (
      <BrowserRouter>
        <Provider store={store}>
          <Switch>
            <Route path="/contribute" component={Contribute} />
            <Route path="/" component={Landing} />
          </Switch>
        </Provider>
      </BrowserRouter>
    );
    

    【讨论】:

    • 啊哈!感谢您的明确回答,非常有帮助。
    • 谢谢,我在迁移到路由器 4 几天后尝试设置这个!
    猜你喜欢
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多