React Router 4 嵌套路由不呈现

React Router 4 Nested Routes not rendering

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

这是父组件:

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 呈现完全空白的页面。知道为什么会这样吗?

发生此行为是因为在父路由

上提到了一个 exact 属性
<Route exact path="/" component={Landing} />

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

你需要写

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