React Router v4渲染组件两次

sac*_*024 3 reactjs 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>
Run Code Online (Sandbox Code Playgroud)

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

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

Ami*_*ebi 13

对我来说,这是因为React.StrictNode它被包裹在 App 组件周围。

它故意双重渲染组件(仅在开发中)来强制您,而不是对组件的某些生命周期事件使用副作用。

其背后的原因记录 在此处


Dom*_*nic 8

对于从 v6+ 来到这里的任何人

exactprop 不再存在,如果未附加通配符,则默认路径是准确的*

然而我仍然得到了双重渲染。我运行了一个产品构建并进行了检查,双渲染消失了,所以可能没有什么可担心的 - 有时钩子在开发模式下运行两次(我猜这就是内部发生的情况)


sac*_*024 5

浏览路由器文档中的多个部分后,我找到了答案。问题是它匹配多条路线

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

  1. / routes / new
  2. / routes /: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>
Run Code Online (Sandbox Code Playgroud)