How to have a callback function after setting the

2019-08-22 17:57发布

trying to callback a function after each individual loop after setting the state. but the callback will execute twice with the most recent state rather then both states.

onAddClick = () => {
    this.state.tempAddList.forEach((id) => {
        console.log("add", id);
        this.setState({modInfo: {...this.state.modInfo, modId: id}},()=>this.addModifier());
    });

};
addModifier = () => {
    console.log(this.state.modInfo);
    EdmApi.insertModifier(this.state.modInfo)
        .then(res => console.log(res))
        .catch(err => console.log(err));

};

1条回答
够拽才男人
2楼-- · 2019-08-22 18:34

this.state shouldn't be used together with setState because state updates are asynchronous. This may result in race condition, which is the problem here.

This is what updater function is for:

this.state.tempAddList.forEach((id) => {
    this.setState(
      state => ({modInfo: {...state.modInfo, modId: id}}),
      ()=>this.addModifier())
    ;
});
查看更多
登录 后发表回答