首页 > 解决方案 > 如何防止withRouter导致重新渲染PureComponent?

问题描述

我可以通过 调用链接history.push("/path")。要访问history,我必须使用withRouterwhich 将多个道具传递给组件。即使路径没有改变,match经过也是不同的。withRouter这会导致PureComponent重新渲染。有没有办法解决这个问题?

例子:

class HomeButton extends PureComponent {
  onClick = () => {
    const { history } = this.props;
    history.push("/");
  }

  render() {
    return <Button onClick={this.onClick}/>
  }
}

export default withRouter(HomeButton);

我使用shallowEqualExplain来检查导致更新的道具。

标签: javascriptreactjsreact-router

解决方案


我有同样的问题。使用shouldComponentUpdate创建的最坏问题以及更多样板代码。另外,文档认为应该不惜一切代价避免这种情况。

相反,我使用了package.json 中的Link组件react-router-dom

CSS

.HomeButton {
  text-decoration: unset;
  color: unset;
}

JS

function HomeButton() {
  return (
    <Link className='HomeButton' to="/"> 
      <Button />
    </Link>
  )
}

export default HomeButton;

注意:您的组件不是纯的,因为withRouter. 如果你删除withRouter它是纯粹的。当然,那么您将不得不使用Link,因为那时您将无法访问history


推荐阅读