【问题标题】:React nested route page not rendering properly as expected反应嵌套路由页面未按预期正确呈现
【发布时间】:2021-03-22 17:29:11
【问题描述】:

我创建了这个有一些嵌套路由的反应组件。问题是嵌套页面组件要么根本不渲染,尽管 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);

【问题讨论】:

  • EditingPlaylist 组件的pathname 的值是多少?你想渲染哪个网址?
  • 试试this.props.match.url 而不是pathname

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

使用urlpath

const { url, path } = this.props.match

到定义的嵌套路由。

所以,在嵌套路由中:

<Switch>
  <Route
    exact
    path={path} // HERE
    render={() => <Searchbar accessToken={this.props.accessToken} />}
  />
  ... 
</Switch>

urlpath 之间存在差异

url: 就是在浏览器中可见的。例如/editing/123。这应该在通过Linkhistory.push 重定向时使用

path: Route 匹配的。例如/editing/:playlistId。这应该在使用Route 定义(嵌套)路径时使用。

来自docs

path - (string) 用于匹配的路径模式。用于构建嵌套的&lt;Route&gt;s

url - (string) URL 的匹配部分。用于构建嵌套的&lt;Link&gt;s

【讨论】:

    猜你喜欢
    • 2019-05-28
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多