同时从多个子组件更新父状态

Dee*_*ngh 5 reactjs

我有一个父组件,它有自己的状态,并且也在子组件之间共享。

在我的子组件中,我有一个表单,对于数据,我创建了一个本地状态。我们称这个子组件为 。

在我的父组件中,有一个按钮,单击该按钮我可以将数据从我孩子的本地状态更新为我父级的状态。我通过将一个标志从父级传递给子级来完成此操作。

另外,我的父母渲染同一个孩子两次,最终代码如下:

const parent = () => {
  const [parentState, setParentState] = useState(null);
  const [submitSignal, setSubmitSignal] = useState(false);

  const handleSave = () => {
    setSubmitSignal(true);
  }

  return (
    <div>
      <div onClick={handleSave}>
        Save Data
      </div>

      <Child
        pos={0}
        key={0}
        parentState={parentState}
        submitSignal={submitSignal}
        setParentState={setParentState}
      />

      <Child
        pos={1}
        key={1}
        parentState={parentState}
        submitSignal={submitSignal}
        setParentState={setParentState}
      />
    </div>
  )
}

const Child = (props) => {
  const [childState, setChildState] = useState(null);

  React.useEffect(() => {
    const { pos, submitSignal, parentState, setParentState } = props;
    if (submitSignal) {
      setParentState(...parentState, ...childState);
    }
  }, [props.submitSignal])

  return (
    <div>
      // A large form which multiple fields
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

现在这里发生的事情是,一旦我从父组件中使submitSignal为true,子组件就会同时收到它并尝试更新父组件的状态。这是一种竞争条件情况,其中子级 0 更新了数据,但在父级状态更新数据之前,子级 1 也更新了父级的状态,从而覆盖/删除了子级 0 添加的内容。

这个你能帮我吗。

PS:我采用这种结构的原因是,在我的孩子中,我有一个非常大的表格,并且相同的表格使用了两次。

hem*_*nni 1

您必须使用回调函数,而不是直接设置父状态。这样,您将在覆盖状态时获得更新的先前状态。

    if (submitSignal) {
      setParentState((pstate)=>{
         return {...pstate,...childstate}
      });
    }
Run Code Online (Sandbox Code Playgroud)

/sf/answers/4797181931/