React Router 4嵌套路由未渲染

wl

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

这是父组件:

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

Shubham Khatri

发生此现象的原因是exact在父路由上提到了一个属性

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

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

你需要写

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

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

还要更改父Route的顺序,因为Switch会渲染第一个匹配项,并且/是部分匹配项,/test因此将/contribute无法工作

您的最终代码如下所示

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章