我正在尝试在我的组件之一中进行嵌套路由。
这是父组件:
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
。它们都不符合所需的路径,因此您会看到空白页
你需要写
<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] 删除。
我来说两句