【问题标题】:How to get multiple children to set one parent state without overwriting each other react js如何让多个孩子设置一个父状态而不相互覆盖反应js
【发布时间】: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


【解决方案1】:

由于他们都或多或少地同时尝试更新状态,因此他们互相践踏。每个孩子都在复制它在state 中的值,然后添加自己,但state 存储组件在渲染时所拥有的内容,并且不会考虑对刚刚发生和正在发生的状态的其他更新通过反应进行批处理。

您可以使用 setState 的函数版本来解决此问题,以确保您始终拥有最新状态:

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

【讨论】:

【解决方案2】:

useState 钩子的设置器也接受一个函数作为参数。此函数接收先前的状态作为 arg。

像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2018-04-30
    • 2018-11-29
    • 1970-01-01
    相关资源
    最近更新 更多