我不想在某些路径上重新渲染我的组件,尝试使用 React.memo 并使用 withRouter HOC 检查当前路径。
React.memo 中的比较函数没有被调用。
function compare(prevProps, nextProps) {
console.log(prevProps,nextProps)
return (prevProps.location.pathname !== '/' && nextProps.location.pathname !== '/')
}
export default React.memo( withRouter(MyComponent), compare);
最佳答案
就这样用吧
function compare(prevProps, nextProps) {
console.log(prevProps,nextProps)
return (prevProps.location.pathname == nextProps.location.pathname)
}
export default withRouter(React.memo(MyComponent, compare));
注意你即将进行的比较
如果你在路由为/
的主页,你的比较有一个流程那么比较函数将始终返回 false
一直导致重新渲染(就像如果 memo
一开始不存在一样),并且如果您位于 /
以外的子 route 喜欢/articles
那么比较将始终返回 true
导致组件一直重新渲染,就像 memo
一样一开始并不存在。
你想要的是一个依赖new
的比较和 old
Prop 有 equal
导致保存重新渲染的东西或导致新的重新渲染的不相等的东西为您呈现新数据。
所以比较应该是这样的
prevProps.location.pathname == nextProps.location.pathname
关于reactjs - React.memo 和 withRouter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60897316/