首页 > 解决方案 > 防止使用 React Router 参数的每个 URI 重新渲染

问题描述

给定以下路由,如果添加或更改了 URI 查询(即?bar2=foo),则MySpecialComponent即使未设置为捕获这些参数,也会重新呈现:

<Route exact path="/foo/:bar" render={props => (<MySpecialComponent/>)}/>

在整个使用过程中,这会导致大量的重新渲染。如何忽略不需要的参数?即在我们关心的更改(/foo/:bar)之前不触发重新渲染。

标签: reactjsreact-nativereact-router

解决方案


我发现使用renderonroute以及自己传递参数是最干净的解决方案(不要用路由器逻辑污染容器):

<Route exact path="/foo/:bar" render={props => (
  // Only pass needed props to avoid unnecessary re-render on ANY URI change
  <MySpecialComponent bar={props.match.params.bar}/>
)}/>

推荐阅读