reactjs - React.memo 和 withRouter

标签 reactjs react-router react-memo

我不想在某些路径上重新渲染我的组件,尝试使用 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/

相关文章:

reactjs - 在某些不支持 BroadcastChannel 的浏览器中,从 Service Worker 发送消息以响应组件

reactjs - 如何在 Gatsby 中创建动态路线

javascript - 在 React Router 中加载 JSON 文件时出现问题

reactjs - react : How to prevent re-rendering child components in `map` ?

javascript - React Virtualized Select css 问题

javascript - 在 useEffect 中调用时 Hook 未更新

javascript - 更新数组 useState react 钩子(Hook)(Next.js)

reactjs - 混淆react-router-dom和react-router-redux

reactjs - 如何防止在react-window的List组件内重新渲染子组件

reactjs - 如何将React.memo与包含子项的组件一起使用