[英]Comparing prevProps and nextProps in a React.memo Component to prevent unnecessary re-rendering but it's acting funny
[英]Component memoized with React.memo() keeps re-rendering
我有一个ParentComponent
看起来像这样:
const ParentComponent = () => {
[product, setProduct] = useState({
name: "Test",
description: "Information goes here..."
})
return(
<ChildComponent product={product} updateProduct={setProduct}/>
);
}
和ChildComponent
如下:
const ChildComponent = ({product, updateProduct}) => {
// some code here
return(
<RichTextEditor content={product.description} update={updateProduct}/>
)
}
const isEqual = () => {
return true; // I want to force the component to never re-render
}
export default React.memo(ChildComponent, isEqual)
这里发生的是我有一个product
对象,其描述由ChildComponent
更新。 每次RichTextEditor
组件中的输入更改时,都会通过updateProduct
设置描述的值。 我知道由于product
的状态更改, ChildComponent
每次都会重新渲染,这是不幸的,因为这可能会导致不需要的效果,例如使RichTextEditor
中的输入字段失去焦点。 因此,我尝试使用始终返回 true 的isEqual
函数强制ChildComponent
永远不要重新渲染。 但它一直在重新渲染,这是为什么呢?
我意识到还有其他设计可以完全避免这个问题,无论如何我可能都会这样做,但在我这样做之前,我想了解为什么我不能强制ChildComponent
不重新渲染。
如果您使用的是useState
、 useContext
或useReducer
,那么组件仍将重新渲染。
这直接来自文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.