React Router v4 渲染组件两次
React Router v4 rendering component twice
这是我的路由器实现
<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 组件两次。对于所有其他路线,它工作正常。
有人可以建议如何解决这个问题吗?
我浏览了 Router Docs 中的多个部分后找到了答案。问题是它匹配多条路线
当用户打开时/profiles/new
它匹配两条路线
- /routes/new
- /路线/: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>
对于从 v6+ 来到这里的任何人
exact
道具不再存在,如果没有附加通配符,路径默认是准确的 *
但是我仍然得到双重渲染。我 运行 构建并检查了产品,双重渲染消失了,所以可能没什么好担心的 - 有时在开发模式下挂钩 运行 两次(我想这就是内部发生的事情)
对我来说,这是因为 React.StrictNode
包裹了 App 组件。
它故意双重渲染组件(仅在开发中)来强制你,而不是在你的某些组件上使用副作用
生命周期事件。
其背后的原因已记录here
这是我的路由器实现
<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 组件两次。对于所有其他路线,它工作正常。
有人可以建议如何解决这个问题吗?
我浏览了 Router Docs 中的多个部分后找到了答案。问题是它匹配多条路线
当用户打开时/profiles/new
它匹配两条路线
- /routes/new
- /路线/: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>
对于从 v6+ 来到这里的任何人
exact
道具不再存在,如果没有附加通配符,路径默认是准确的 *
但是我仍然得到双重渲染。我 运行 构建并检查了产品,双重渲染消失了,所以可能没什么好担心的 - 有时在开发模式下挂钩 运行 两次(我想这就是内部发生的事情)
对我来说,这是因为 React.StrictNode
包裹了 App 组件。
它故意双重渲染组件(仅在开发中)来强制你,而不是在你的某些组件上使用副作用 生命周期事件。
其背后的原因已记录here