防止 useContext 值更新映射组件的每个实例



我有一长串组件,它从我的上下文中获取一个值。

Component有一个唯一的 ID,并且还知道哪个是"当前"ID。我只希望idcurrentId匹配的ComponentmyContext的值发生变化时更新。

const ComponentList = () => {
return(
<>
{data.map((d,i) => 
<Component key={i} id={d.id} />
}
</>
)
}
const Component = ({id}) => {
const {value} = useContext(MyContext);
const {currentId} = useContext(OtherContext);
//only re-render if `id === currentId` and `value` changes
return (
<h1>{value}</h1>
)
}

请注意,来自 myContext 的值并不关心哪个组件id是当前id

我认为答案就在记忆的某个地方,但我还没有成功找到它。(我能够通过做const {value} = id === currentId ? useContext(MyContext) : {value: null}来让它按照我的意图工作,但这显然是不行的)

我已将其抽象为一个非常通用的示例,但是如果需要更多上下文(哈哈),我可以进一步解释我的用例。

似乎 React.memo 就是答案,而且相当简单; 只是一开始没有看到它。

我把Component包裹在备忘录中,并添加了我自己的条件。

const ParentComponent = (props) => {
const {value} = useContext(MyContext);
const {currentId} = useContext(OtherContext);
return (
<Component id={props.id} value={value} currentId={currentId} />
)
}
const Component = memo(
({value}) => {
return (
<h1>{value}</h1>
)
},
(prev, next) =>
prev.value === next.value || prev.id !== next.currentId
);

如果上一个值和下一个值相等,或者 id 与当前 ID 不匹配,则这基本上不会更新。

最新更新