javascript - 如何防止withRouter导致重新渲染PureComponent?
问题描述
我可以通过 调用链接history.push("/path")
。要访问history
,我必须使用withRouter
which 将多个道具传递给组件。即使路径没有改变,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来检查导致更新的道具。
解决方案
我有同样的问题。使用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
。
推荐阅读
- haskell - 使 GHCi 以十进制形式打印。
- r - R闪亮的数字输入步骤和最小值交互
- c# - 从 LINQ 填充的 DataGrid 中提取 SelectedItem 事件中的数据
- r - 在 R 中使用带状图有条件地绘制 pch
- java - 在这里调用实例方法或声明变量更好吗?
- android - 调整图像宽度以匹配父级并根据 ImageView 中的纵横比调整高度
- ios - 尝试在表格视图中添加虚线边框分隔符
- encoding - 在 python3.6 中使用 aiohttp 时出现 UnicodeEncodeError
- ios - 将复制的数字粘贴到 UITextView 时如何更改复制的数字?
- graph - 每次 tetrimono 登陆时,ti-basic 俄罗斯方块更新列表