Reactjs 将两个函数作为回调传递给this.setState
我希望在运行此.setState()之后有多个回调 此代码有效,Reactjs 将两个函数作为回调传递给this.setState,reactjs,Reactjs,我希望在运行此.setState()之后有多个回调 此代码有效,此工作已打印 savePitch(e){ this.setState({savedPitches: [...this.state.savedPitches, this.state.addNewPitch]}) this.setState({addNewPitch: { id: this.state.addNewPitch.id + 1, pitchNam
此工作已打印
savePitch(e){
this.setState({savedPitches: [...this.state.savedPitches, this.state.addNewPitch]})
this.setState({addNewPitch: {
id: this.state.addNewPitch.id + 1,
pitchName: '',
shortCut: '',
subject: '',
pitch: ''
}},
() => {console.log('this worked')},
)
this.toggleNewPitchForm()
}
但是,如果我想运行两个函数,我尝试了下面的方法,但没有达到预期效果
savePitch(e){
this.setState({savedPitches: [...this.state.savedPitches, this.state.addNewPitch]})
this.setState({addNewPitch: {
id: this.state.addNewPitch.id + 1,
pitchName: '',
shortCut: '',
subject: '',
pitch: ''
}},
() => {console.log('this worked')},
() => {console.log('then this worked')},
)
this.toggleNewPitchForm()
}
我应该做哪些更改才能按预期运行 只需在arrow函数中顺序调用方法:
this.setState(..., () => {
(() => { console.log('one') })()
(() => { console.log('two') })()
}
只需定义将调用其他方法的方法
const myMethod = () => {
myMethod1();
myMethod2();
myMethod3();
};
this.setState({addNewPitch: {...}}, myMethod);
setState
只使用一个回调函数,而不是两个。我很想知道这背后的原因是什么,为什么需要第二个回调函数?顺便问一下,您知道,setState
调用……有没有办法将两个函数都包含在一个回调中?这是否回答了您的问题?我得到了这个错误:App.js:174未捕获类型错误:(中间值)(…)不是函数(但这就是我要找的)这个答案帮助了我!:)我还得到了同样的错误uncaughttypeerror:(中间值)(…)不是函数
,但我只是缺少iife的第二组括号。