我正在尝试在我的组件之一中进行嵌套路由。
这是父组件:
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呈现完全空白的页面。知道为什么会这样吗?
ArtistList
/
/test
发生此现象的原因是exact在父路由上提到了一个属性
exact
<Route exact path="/" component={Landing} />
因此,发生的事情是react-router看到了一条/test匹配的路径,然后尝试从顶层开始进行匹配。它看到两条路线,一条是exactly /,另一条是/contribute。它们都不符合所需的路径,因此您会看到空白页
exactly /
/contribute
你需要写
<Route path="/" component={Landing} />
因此,当您执行此操作时,它将看到部分/匹配的内容/test,然后尝试在要查找的landing组件中找到匹配的路由。
landing
还更改父Route的顺序,因为Switch会渲染第一个匹配项,并且/是部分匹配项,/test因此将/contribute无法工作
Switch
您的最终代码如下所示
const App = () => ( <BrowserRouter> <Provider store={store}> <Switch> <Route path="/contribute" component={Contribute} /> <Route path="/" component={Landing} /> </Switch> </Provider> </BrowserRouter> );