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

时间:2021-05-28 12:53:55

标签: reactjs setstate

我正在开发一个带有几个表单的 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 时没有任何反应。

链接到我的 github 存储库:here。有问题的函数在 App.js 中。

1 个答案:

答案 0 :(得分:1)

正如 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 } })
);

现在一切都按预期运行。