如何防止在 react-router v4 中匹配两条路由?

How to prevent both routes from being matched in react-router v4?

如果路径为/posts/new,下面的PostsNewPostsShow两个组件都会被渲染,并且匹配:idid单词 new 而不是数字:

ReactDOM.render(
  (
    <Provider store={createStoreWithMiddleware(reducers)}>
      <Router>
        <App>
          <Route exact={true} path="/" component={PostsIndex} />
          <Route path="/posts/new" component={PostsNew} />
          <Route path="/posts/:id" component={PostsShow} />
        </App>
      </Router>
    </Provider>
  ),
  document.querySelector('#root')
);

在App.js中:

  <div>
    <h1>An awesome App</h1>
      {this.props.children}
  </div>

怎么会/posts/new不匹配两次呢?

我们称之为 "ambiguous routes",我们的网站上有一个示例 here

Switch 组件应该可以解决这个问题。

ReactDOM.render(
  (
    <Provider store={createStoreWithMiddleware(reducers)}>
      <Router>
        <App>
          <Switch>
            <Route exact={true} path="/" component={PostsIndex} />
            <Route path="/posts/new" component={PostsNew} />
            <Route path="/posts/:id" component={PostsShow} />
          </Switch>
        </App>
      </Router>
    </Provider>
  ),
  document.querySelector('#root')
);