从子组件返回时获取初始 useState 列表值以保存数据而不是当前状态

Getting initial useState list values when returning from a sub componet to save data instead of current state

我在一个简化的代码示例中重现了我的问题。 请按照以下步骤重现它:

  1. 单击三个列表项之一 以编辑关闭-canvas 框中的值。
  2. 更改值并单击保存按钮。
  3. Select 要编辑和保存的不同项目。
  4. 注意:原来编辑的项目已经恢复到初始状态。 我在保存方法中有 console.logging 以显示列表(状态)不是当前(可见)版本而是初始状态。

Sandbox code example

我有一个不雅的解决方案(解决方法),我将其作为答案,但它没有解释发生了什么或为什么会发生这种情况。我的页面上有 3 个这样的 off-canvas 编辑器,其中一个确实按预期工作,但另外两个在父级中调用它们的保存函数时处于松散状态。

这是我糟糕(丑陋)的解决方法:

  1. 将状态 object (myList) 传递给 props object 中的 child。

App.js

  function open(e, item, itemIndex) {
    setPropArgs({ ...propArgs, editThis: item, index: itemIndex, show: true, itemList: myList });
  }
  1. Return 列表返回 parent 在保存方法调用中并使用传递的变量而不是状态。

MyEditor.js

    <Button type="button" onClick={(e) => props.save(edit, props.index, props.itemList)}>
      Save
    </Button>

App.js

  function save(edit, index, itemList) {
    // console.log(myList);
    const newList = [...itemList];
    newList[index] = edit;
    setMyList(newList);
    setPropArgs({ ...propArgs, show: false });
  }

这很糟糕,因为 MyEditor 不需要知道任何关于 parent 的信息,它根本不会读取或编辑列表,并且不需要传递一份可能会过时的状态(如果我没有用 canvas 阻塞)。

好的...我找到了我要找的答案。 感谢Marco Nisi for

我的分叉代码解决方案here

解决方案是将回调(保存函数)移动到显示 canvas 时创建,而不是在初始化功能组件时创建状态的更新克隆。如果您有一个在后台更新状态的示例,或者如果 off-canvas 没有阻止其他编辑,我仍然认为这是有问题的。 注意:您不需要在 open 函数中定义的回调,但它确实需要添加(替换)到那里的 props 对象。

  function open(e, item, itemIndex) {
    save = (edit, index) => {
      console.log(myList);
      const newList = [...myList];
      newList[index] = edit;
      setMyList(newList);
      setPropArgs({ ...propArgs, show: false });
    };
    setPropArgs({
      ...propArgs,
      editThis: item,
      index: itemIndex,
      show: true,
      save: save
    });
  }