[英]How to force React.memo render component only once (on initial load)?
在我的父組件中,我有一個子組件,我只需要渲染一次 - 在最開始時。 因為在下一頁重新加載之前,里面的數據永遠不會改變。 我嘗試做的是以某種方式強制 React.memo 阻止渲染這個子組件:
const ParentComponent = (props) => {
const ChildComponent = React.memo(({items}) => {
const { param1, param2, param3 } = items;
...
return (<Box>..</Box>);
}, (prev, nxt) => true); // Here I try to force no render
return (<Box>
<ChildComponent items={{
param1: 'some val..',
param2: 'some val..',
param3: 'some val..',
}} />
...
</Box>);
}
但是子組件仍然會在每次父狀態更改時重新渲染。 難道我做錯了什么?
首先,在另一個組件中定義一個組件是一種不好的做法,因為
因此,為了讓您的生活更輕松,請提取ChildComponent
。
const ChildComponent = props => {
return (
<Box>
{/* do whatever you like */}
</Box>
);
};
export default memo(ChildComponent);
const ParentComponent = props => {
const items = {
param1: 'some val..',
param2: 'some val..',
param3: 'some val..',
};
return (
<Box>
<ChildComponent
items={items}
// You can also pass other props from the ParentComponent, in case ChildComponent needs it
/>
</Box>
);
};
當然,很少有人可以通過使用 memoization 來實現這一點。 但首先我建議您將ChildComponent
定義移到ParentComponent
之外。 這兩種方式都要求您像您所做的那樣將ChildComponent
包裝在 React.memo 中,所以這部分是可以的。
第一種方法是確保items
道具的值(參考)是穩定的,如果你想避免不必要的子組件重新渲染。 因此解決方案是將items
對象包裝在 useMemo 中並僅計算一次以使引用變得穩定。
第二種方法是使用 React.memo 函數的第二個參數,並傳遞自定義isEqual
函數以確定您的道具何時更改,例如對items
道具的后續值執行深度相等檢查,以避免不必要的重新渲染。 更多關於這個可以在這里找到反應備忘錄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.