首页 > 解决方案 > React Router v4 渲染组件两次

问题描述

这是我的路由器实现

<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 组件两次。对于其他所有路线,它都运行良好。

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

标签: reactjsreact-router-v4

解决方案


在浏览了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>

推荐阅读