嵌套路由器无法正确呈现组件

时间:2018-06-17 23:12:15

标签: reactjs 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 / 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 / followers上的空白页面呈现。

有什么想法,为什么这个过程不适用于我的个人资料组件,但适用于设置组件?

编辑**我尝试的第三种方法是将match.params放入路径名中。例如。

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

这给了我一个类似的结果。

1 个答案:

答案 0 :(得分:0)

问题是<Route path="/:username" exact component={Timeline} />会匹配比你想象的更多的路线。

例如,它将匹配:

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

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

相关问题