如何使用 setState 回调函数进行条件函数调用

How to make a conditional function call using setState callback function

下面的功能逻辑有效,但通过阅读各种帖子和 SO 问题,了解到应该避免这种情况。所以,我试图在 setState 中使用回调来引用以前的状态。 saveOptions 函数调用取决于状态变化。

转换了下面的代码

validateOnSave() {
    const copy = this.state.codeSelectionIsInvalid;
    copy[0] = !this.state.reasonCode;
    copy[1] = !this.state.remarkCode;
    copy[2] = !this.state.otherCode;
    this.setState({ codeSelectionIsInvalid: copy });

   if (!copy[0] && !copy[1] && !copy[2]) {
      this.saveOptions();
    }
  }

使用回调

validateOnSave() {
    this.setState(prevState => ({
      codeSelectionIsInvalid: [!prevState.reasonCode, !prevState.remarkCode, !prevState.otherCode],
      },
      () => {
        if(!prevState.reasonCode && !prevState.remarkCode && !prevState.otherCode) {
          this.saveOptions();
        }
      }
    )
}

错误:

{ SyntaxError: OptionsView.jsx: Unexpected token, expected "," (110:2)

  108 |       }
  109 |     )
> 110 |   }

但这不是很有效。给我语法错误。我哪里错了? 感谢您的帮助!

在第一次回调时,您忘记了关闭 ) 来完成 shorthand 箭头功能,即

prevState => ({
  codeSelectionIsInvalid: [!prevState.reasonCode, !prevState.remarkCode, !prevState.otherCode],
}), // <-- closing bracket
() => { ...