![](/img/trans.png)
[英]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.