【发布时间】:2022-01-06 00:49:18
【问题描述】:
我有 3 个子组件更新同一个父状态对象。 我希望每个孩子只更新对象中自己的字段。我如何做到这一点?
我想这样做,以便我可以跟踪每个孩子的状态。
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>);
};
【问题讨论】:
-
尝试去掉'true'和'false'中的单引号..比较时可能会出现问题..
标签: reactjs typescript