【发布时间】:2021-01-14 23:01:55
【问题描述】:
我的项目的状态包括嵌套动物的列表,例如:
{"europe":{"air":{name:"warbler", points:0}}}
我的组件是根据这些数据生成的,在最低级别(动物本身),有一个按钮当前正在触发一系列回调到最高级别,开始向 reducer 调度。每次单击按钮时,来自每个大陆的所有组件都会重新渲染。 即使每个级别的组件都需要来自状态对象的一些数据,实现 useContext 会更好吗? 我尝试实现 useCallback,以防止重新渲染,但我不知道是哪些回调导致了它。优化渲染一系列嵌套组件(没有 redux)的最佳方法是什么?
App组件内部
{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>
【问题讨论】:
标签: reactjs typescript performance react-hooks react-functional-component