React router:route渲染两个组件

时间:2018-05-02 12:41:15

标签: reactjs react-router react-router-v4

我的反应应用中有以下路线:

<Route exact path="/" component={HomeScreen} />
<Route exact path="/:category" component={HomeScreen} />
<Route exact path="/:category/:id" component={PostDetailScreen} />
<Route exact path="/posts/new" component={CreatePostScreen} />

当我去/ post / new我的应用程序不仅渲染CreatePostScreen而且还渲染PostDetailScreen。我认为它解释了:category = posts和:id = new。

然而,我被卡住了。我究竟做错了什么?我只想让/ posts / new路由渲染CreatePostScreen。

2 个答案:

答案 0 :(得分:1)

React路由器将“posts”解释为类别,将“new”解释为ID。

更改路由组件的顺序,并使用Switch组件,如下所示:

<Switch>
    <Route exact path="/" component={HomeScreen} />
    <Route exact path="/posts/new" component={CreatePostScreen} />
    <Route exact path="/:category" component={HomeScreen} />
    <Route exact path="/:category/:id" component={PostDetailScreen} />
</Switch>

答案 1 :(得分:1)

试试这个

<Switch>
  <Route exact path="/" component={HomeScreen} />
  <Route exact path="/posts/new" component={CreatePostScreen} />
  <Route exact path="/:category" component={HomeScreen} />
  <Route exact path="/:category/:id" component={PostDetailScreen} />
</Switch>

/posts/new是满足/:category/:id的有效路径,即您的类别为posts,ID为new

<Switch>中放置路线会先找到匹配的路线,在此处显示更多信息https://reacttraining.com/react-router/web/api/Switch