以下函数逻辑有效,但是通读各种帖子和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 | }
但这不是很有效。给我语法错误。我在哪里错了? 感谢您的帮助!
答案 0 :(得分:1)
在第一个回调中,您忘记了关闭)
来完成速记箭头功能,即
prevState => ({
codeSelectionIsInvalid: [!prevState.reasonCode, !prevState.remarkCode, !prevState.otherCode],
}), // <-- closing bracket
() => { ...