React将两个函数作为回调传递回this.setState

时间:2017-11-12 19:47:10

标签: reactjs

我希望在运行this.setState()

后有多个回调

此代码有效且float(1000000000000000001)

this work is printed

但是,如果我想要运行两个函数,我尝试了下面但它没有按预期工作。

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()
    }

我应该做些什么更改才能按预期运行?

2 个答案:

答案 0 :(得分:3)

只需在箭头函数中按顺序调用方法:

this.setState(..., () => {
    (() => { console.log('one') })()
    (() => { console.log('two') })()
}

答案 1 :(得分:1)

只需定义将调用其他方法的方法。

const myMethod = () => {
  myMethod1();
  myMethod2();
  myMethod3();
};

this.setState({addNewPitch: {...}}, myMethod);