【问题标题】:Nested router not rendering components correctly嵌套路由器未正确渲染组件
【发布时间】:2018-11-26 19:26:51
【问题描述】:

我在 react-router 中遇到了一个奇怪的嵌套路由错误,我正在努力修复。

我有两个组件,其中有多个路由。一个是设置组件,另一个是配置文件组件。在我的设置组件中,一切正常。

我的组件文件夹中有三个文件(index.js、editprofile.js 和 password.js)。我在我的索引文件中导入组件。然后像这样渲染它们。

index.js // settings component
...html that renders across all routes
<Route path="/account/settings" exact component={EditProfile} />
<Route path="/account/settings/password" component={Password} />

这按计划进行。在 /account/settings 上,编辑配置文件组件呈现,当我链接到 /account/settings/password 时,密码组件出现,而编辑配置文件组件消失了。

现在我遇到的错误是当我尝试在我的配置文件组件中做同样的事情时。我的个人资料组件中有类似的文件结构(index.js、timeline.js、followers.js、following.js ...)。我将它们导入我的 index.js 并像这样在组件中呈现它们。

index.js // profile component
...html that renders across all routes
<Route path="/:username" exact component={Timeline} />
<Route path="/:username/followers" component={Followers} />
...other <Route />'s

这会正确加载时间轴组件,但是当我链接到任何其他路由时,它会加载一个空白页面。作为替代方案,我尝试编辑如下路径:

<Route path={{pathname: '/' + this.props.user.Username}} exact component={Timeline} />
<Route path={{pathname: '/' + this.props.user.Username + '/followers'}} component={Followers} />

这导致关注者组件在应该是 /:username 上呈现,而空白页面在 /:username/followers 上呈现。

您知道为什么此过程不适用于我的配置文件组件,但适用于设置组件吗?

Edit** 我尝试的第三种选择是将 match.params 放入路径名中。例如。

<Route path={{ pathname: this.props.match.params.username }} component={Timeline} />
<Route path={{ pathname: this.props.match.params.username + '/followers' }} component={Followers} />

这给了我与之前类似的结果。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    问题是&lt;Route path="/:username" exact component={Timeline} /&gt; 匹配的路由比你想象的要多。

    例如,它会匹配:

    /about    // username = about
    /followers // username = followers
    

    等等。您需要使其更具体或将其声明为最后一条路线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2020-12-22
      相关资源
      最近更新 更多