我不想在某些路径上重新渲染我的组件,尝试使用React.memo并使用withRouter HOC检查当前路径。
不会调用React.memo中的compare函数。
function compare(prevProps, nextProps) {
console.log(prevProps,nextProps)
return (prevProps.location.pathname !== '/' && nextProps.location.pathname !== '/')
}
export default React.memo( withRouter(MyComponent), compare);发布于 2020-10-20 00:44:57
就像这样使用它
function compare(prevProps, nextProps) {
console.log(prevProps,nextProps)
return (prevProps.location.pathname == nextProps.location.pathname)
}
export default withRouter(React.memo(MyComponent, compare));注意你将要做的比较
你的比较有一个流程,如果你在主页面的路由是/,那么比较函数将总是返回false,导致重新渲染所有的时间(就像如果memo不存在在第一个地方),如果你在/以外的子路由中,比如/articles,那么比较将总是返回true,导致组件一直重新渲染,就像memo一开始不存在一样。
你想要的是一个依赖于new和old属性的比较,它有equal的东西,这会导致保存重新渲染,或者有不相等的东西,会导致新的重新渲染为你渲染新的数据。
所以比较应该是这样的
prevProps.location.pathname == nextProps.location.pathname发布于 2021-07-14 20:39:59
谢谢你的问题,两个月前它对我很有帮助。
memo函数获取一个组件和一个function,它将被调用来决定React是否需要重新呈现,如果函数返回true,组件将不会重新呈现,无论如何,如果函数返回false,那么现在属性就不同了,React对您的组件执行re-render。
现在:为了在传递给memo的function中正确访问pathname,那么memo应该用withRouter包装,而不是相反,withRouter包装一个组件(它不知道组件的记忆版本,它只是包装它),并将其传递给路由道具。
作为第二个参数传递给memo的function现在可以访问previous和new属性,并进行前面讨论的比较(其中每个属性都包含您想要的完整路由细节)。
import { memo } from 'react';
function propsAreEqualBasedOnPathname(prevProps, nextProps) {
return prevProps.location.pathname == nextProps.location.pathname;
}
withRouter(memo(MyComponent), propsAreEqualBasedOnPathname);最后,要特别注意如何在compare function中进行比较,因为一些错误可能会永远阻止您的组件在将来重新呈现。
我发现结合使用memo和withRouter对于提高React组件的performance非常重要,特别是如果组件是一个充满细节和获取逻辑的页面,这可能会花费你一些时间来呈现,所以每次重新呈现你保存的时候,都会增加你的页面性能。
https://stackoverflow.com/questions/60897316
复制相似问题