[英]Avoid unneccessary re-rendering in React dynamic nested components
我的項目的狀態包括嵌套動物列表,例如:
{"europe":{"air":{name:"warbler", points:0}}}
我的組件是根據這些數據生成的,在最低級別(動物本身),有一個按鈕當前正在觸發一系列到最高級別的回調,開始對減速器的調度。 每次單擊按鈕時,來自各大洲的所有組件都會重新渲染。 即使每個級別的組件都需要來自狀態對象的一些數據,實現 useContext 會更好嗎? 我嘗試實現 useCallback,以防止重新渲染,但我不知道是哪個回調導致了它。 優化渲染一系列嵌套組件(沒有 redux)的最佳方法是什么?
內部應用組件
{Object.entries(state.animalData).map(([continent, areas]) => (
<Continent
key={continent}
areas={areas}
totals={state.totals.continents[continent]}
handleVote={(
num: number,
animal: string,
area: string
) => triggerChange(num, animal, area, continent)}
/>
))}
大陸組件內部
<Area
key={area}
area={area}
animals={animals}
onVote={(num: number, animal: string) =>
handleVote(num, animal, area)
}
/>
內部區域組件
{animals.map(animal => (
<Animal
key={animal.name}
animal={animal}
voted={(num: number) => onVote(num, animal.name)}
/>
))}
內部動物組件
<div>
<h4>{animal.name}</h4>
<div>
<button onClick={voted(+1)}> Upvote </button>
<button onClick={voted(-1)}> Downvote </button>
</div>
<h4>{`${animal.points} Points`}</h4>
<hr />
</div>
您的組件會觸發重新渲染,因為您在任何地方都使用內聯定義的函數,而這些函數並不穩定。 您可以使用useCallback
( https://reactjs.org/docs/hooks-reference.html#usecallback ) 鈎子來防止重新渲染。
但是您也可以使用保存voted
回調的上下文提供程序(如您所建議的那樣)。 這樣您就不必使用道具鑽孔來將函數傳遞給需要它的組件。
這里詳細解釋了基本解決方案: https : //medium.com/@jeromefranco/how-to-avoid-prop-drilling-in-react-7e3a9f3c8674
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.