React setState和Promise中的竞争条件

时间:2019-06-25 00:17:16

标签: reactjs

在我的上下文中,我有一个LocalFunction可以返回承诺。

LocalFunction: () => Promise<void>

LocalFunction: () => {
    return externalCall.getBooks().then((books) => {
        this.setState({ Books: books })
    })
}

我可以基于Context状态下更新后的Books对象在另一个组件中调用此函数,例如:

this.props.LocalFunction().then(() => {
    // do something with this.props.Context.Books
})

但是我知道React会批量更新状态。那么在调用LocalFunction时,Books状态不会随着新书的更新而改变吗?

我知道一种避免它的方法是将LocalFunction包装在新的Promise中并在this.setState({ Books: books }, resolve)中解决它,但我想避免这样做。

1 个答案:

答案 0 :(得分:0)

如何使用异步/等待?

v1 <- c("{\"\"element\"\":\"\"IAB1_4\"\"}", "{\"\"element\"\":\"\"IAB19_3\"\"}", 
"{\"\"element\"\":\"\"IAB19_16\"\"}", "{\"\"element\"\":\"\"IAB9_11\"\"}", 
"{\"\"element\"\":\"\"IAB19_5\"\"}", "{\"\"element\"\":\"\"IAB18_1\"\"}"
)
LocalFunction: async (needUpdate = false) => {
    const result = await externalCall.getBooks();
    if(needUpdate){
        this.setState({ Books: result })
    }
    return result;
}

何时需要更新状态

this.props.LocalFunction().then((res) => {
    console.log(res)
    // do something with this.props.Context.Books
})