【发布时间】:2020-03-28 04:40:36
【问题描述】:
我不想在某些路径上重新渲染我的组件,尝试使用 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);
【问题讨论】:
-
来自React docs上的
React.memo:此方法仅作为性能优化存在。不要依赖它来“阻止”渲染,因为这可能会导致错误。 -
为什么你试图阻止重新渲染?其他一些潜在的问题?也许还有其他方式来构建您的组件,这样特定的组件就不会不必要地渲染。
-
为了优化,我必须防止不必要的重新渲染。 compare 函数具有特定目的 - 检查是否需要渲染。但我无法调用它。
-
你应该在 MyComponent 中 use the hooks 因为 withRouter 不会重新渲染,除非父级重新渲染。
-
@HMR 感谢您的回答。由于备忘录无法访问状态值,因此无法渲染的问题仍然存在。
标签: reactjs react-router react-memo