如何让多个子级设置一个父级状态而不覆盖另一个react js



我有三个子组件,它们更新相同的父状态对象。我希望每个子对象只更新对象中自己的字段。我该如何做到这一点?

我想这样做,这样我就可以跟踪每个孩子的状态


const Child = ({ setState, state, which }) => {
// this was a hack to stop the infinite rerendering - ideally i don't do this but i don't know how to deal with it
const [hasUpdated, setHasUpdated] = useState(false);

useEffect(() => {
if (!hasUpdated){
console.log(`${which} has updated`);
setHasUpdated(true);
setState({
...state,
[which]: false, // this can be true

});
}
}, [setState, which, state]);
return <div>{which === 'b' ? 'was b' : 'not b'}</div>;
};
const Parent = () => {
const [state, setState] = useState({ a: true, b: true, c: true }); <-----------------
// they should all be set to false but they are not - only C is set to false
// i want child a to only update the a key without affecting the rest. How do I do this?
const children = ['a', 'b', 'c'].map((which) => {
return (
<div>
<Child setState={setState} state={state} which={which} />
^--- {state[which] ? 'true': 'false'}
</div>
);
});

useEffect(() => {
console.log(state);
}, [state])
return (<div>{children}</div>);
};

由于他们或多或少都在试图同时更新状态,所以他们互相践踏。每个子级都在复制它在state中的值,然后添加它自己,但state存储组件在渲染时的内容,并且不会考虑刚刚发生的、正在由react批处理的状态的其他更新。

你可以通过使用setState的函数版本来修复这个问题,这样你就可以确保你总是有最新的状态:

setState(prev => {
return {
...prev,
[which]: false
}
});

useState钩子的setter也接受一个函数作为参数。此函数接收以前的状态作为arg。

像这样:

// In Child
useEffect(() => {
setState((prevState) => ({
...prevState,
[which]: false, // this can be true
}));
}, [setState, which]);

最新更新