反应 setState 不更新我的功能之一的状态

react setState not updating state in one of my functions

我正在开发一个带有几个表单的 React 应用程序,我正在尝试为输入项实现一个编辑表单。该函数首先以预填充的形式打开列表项。 editItem 函数当前如下所示:

editItem(event) {
    event.preventDefault();
    const target = event.target.parentNode.parentNode;
    const { key } = target.dataset;
    const { className } = target;
    const currState = { ...this.state[className] };
    const currItem = currState.list[key];
    for (let i in currItem) {
      if (i !== "list" && i !== "hidden") {
        currState[i] = currItem[i]
      }
    }
    this.setState({ [className]: currState });
    this.hideUnhide({target: {name: className}});
 

     }

我已通过控制台日志确认 currState 已正确设置为我要查找的值,并且我没有遇到异步问题。我正在使用相同的格式在我的应用程序的其他功能中设置状态,并且所有其他功能都正常工作。如果我在同一个地方直接改变状态,我会得到我正在寻找的行为(填充表单字段),但是当我使用 setState 时没有任何反应。

Link 到我的 github 回购:here。有问题的函数在 App.js.

正如 Brian Thompson 在他的评论中指出的那样,事实证明,在我的 setState 之后直接调用 hideUnhide 函数也使用了 setState,并用之前的状态覆盖了第一个 setState 调用:

  hideUnhide(event) {
    const { name } = event.target;
    const currState = { ...this.state[name] };
    if (currState.hidden === true) {
      currState.hidden = false;
    }
    this.setState({ [name]: currState });
  }

防止这种情况的方法是使用 hideUnhide 作为对 editItem 中 setState 的回调:

this.setState({ [className]: currState }, () =>
  this.hideUnhide({ target: { name: className } })
);

现在一切正常。