React Router v4渲染组件两次

问题描述 投票:1回答:1

这是我的路由器实现

<BrowserRouter>
  <div>
    <Route exact path="/" component={ProfilesIndex} />
    <Route exact path="/profiles" component={ProfilesIndex} />
    <Route exact path="/profiles/new" component={ProfileEditor} />
    <Route exact path="/profiles/:id" component={ProfileEditor} />
  </div>
</BrowserRouter>

当我浏览/profiles/new路径时,它会渲染ProfileEditor组件两次。对于其他所有路线,它工作正常。

有人可以建议如何解决这个问题吗?

reactjs react-router-v4
1个回答
4
投票

我在浏览Router Docs的多个部分后找到了答案。问题是它匹配多条路线

当用户打开/profiles/new时,它匹配两条路线

  1. /路由/新
  2. /路由/:ID

因为:id就像一个通配符*,它也匹配new字,因此两个路由都匹配,因此组件被渲染两次。

解决方案是使用Switch包装路由,如果您不想匹配多个路由。

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={ProfilesIndex} />
    <Route exact path="/profiles" component={ProfilesIndex} />
    <Route exact path="/profiles/new" component={ProfileEditor} />
    <Route exact path="/profiles/:id" component={ProfileEditor} />
  </Switch>
</BrowserRouter>
© www.soinside.com 2019 - 2024. All rights reserved.