我创建了这个具有一些嵌套路由的 react 组件。问题在于,尽管 URL 发生了变化,嵌套页面组件要么根本没有呈现,要么只是返回一个空白页面。
我尝试了其他帖子中的建议,例如在父路由中添加/删除 exact
,但仍然无效。
以下是我的代码:
// the parent component
<div className="App">
<Router>
<Navbar />
<Switch>
<Route exact path="/" render={() => <MyPage accessToken={accessToken} />}/>
<Route path="/editing/:playlistId" render={(props) =>
<EditingPlaylist {...props} accessToken={accessToken} />} />
</Switch>
</Router>
</div>
//the child component EditingPlaylist
render() {
const { pathname } = this.props.location;
return (
<div className="editing">
<Switch>
<Route exact path={pathname} render={() =>
<Searchbar accessToken={this.props.accessToken} />} />
<Route path={`${pathname}/test`} component={<p>Test</p>} />
<Route path={`${pathname}/album/:albumId`} render={
(props) => <AlbumPage {...props} accessToken={this.state.accessToken} />} />
<Route path={`${pathname}/artist/:artistId`} render={
(props) => <ArtistProfile {...props} accessToken={this.state.accessToken} />} />
</Switch>
</div>)
}
export default withRouter(EditingPlaylist);
答案 0 :(得分:1)
使用 url
和 path
:
const { url, path } = this.props.match
定义嵌套路由。
因此,在嵌套路由中:
<Switch>
<Route
exact
path={path} // HERE
render={() => <Searchbar accessToken={this.props.accessToken} />}
/>
...
</Switch>
url
和 path
之间存在区别:
url
:它是浏览器中可见的内容。例如/editing/123
。这应该在通过 Link
或 history.push
path
:它是路由匹配的内容。例如/editing/:playlistId
。这应该在使用 Route
定义(嵌套)路径时使用。
来自docs:
<块引用>path -(字符串)用于匹配的路径模式。用于构建嵌套的 <Route>
s
url -(字符串)URL 的匹配部分。用于构建嵌套的 <Link>
s