this.setState 是否在反应中返回承诺 [英] Does this.setState return promise in react
问题描述
我使我的 componentWillMount()
异步.现在我可以将 await
与 setState
一起使用.
I made my componentWillMount()
async. Now I can using await
with the setState
.
这是示例代码:
componentWillMount = async() => {
const { fetchRooms } = this.props
await this.setState({ })
fetchRooms()
}
所以这里的问题是 this.setState
返回 promise 因为我可以使用 await
吗?
So question here is this.setState
returns promise because I can use await
with it?
编辑
当我放置 await 然后它按顺序运行 1, 2, 3
而当我删除 await 然后它运行 1, 3, 2
??
When I put await then it runs in a sequence 1, 2, 3
And when I remove await then it runs 1, 3, 2
??
componentWillMount = async() => {
const { fetchRooms } = this.props
console.log(1)
await this.setState({ } => {
console.log(2)
})
console.log(3)
fetchRooms()
}
推荐答案
setState
通常不与 Promise 一起使用,因为很少有这样的需要.如果在状态更新 (fetchRooms
) 后调用的方法依赖于更新的状态 (roomId
),则它可以通过另一种方式访问它,例如作为参数.
setState
is usually not used with promises because there's rarely such need. If the method that is called after state update (fetchRooms
) relies on updated state (roomId
), it could access it in another way, e.g. as a parameter.
setState
使用回调并且不返回承诺.由于很少需要这样做,因此创建一个不使用的承诺会导致开销.
setState
uses callbacks and doesn't return a promise. Since this is rarely needed, creating a promise that is not used would result in overhead.
为了返回承诺,可以承诺 setState
,如 this answer.
In order to return a promise, setState
can be promisified, as suggested in this answer.
发布的代码与 await
一起使用,因为它是一个 hack.await ...
是 Promise.resolve(...).then(...)
的语法糖.await
产生一个滴答延迟,允许在状态更新完成后评估下一行,这允许按预期顺序评估代码.这与:
Posted code works with await
because it's a hack. await ...
is syntactic sugar for Promise.resolve(...).then(...)
. await
produces one-tick delay that allows to evaluate next line after state update was completed, this allows to evaluate the code in intended order. This is same as:
this.setState({ roomId: room && room.roomId ? room.roomId : 0 }, () => {
console.log(2)
})
setTimeout(() => {
console.log(3)
});
无法保证订单在不同条件下会保持不变.此外,第一个 setState
回调不是检查状态是否更新的合适位置,这就是第二个回调的用途.
There's no guarantee that the order will stay same under different conditions. Also, first setState
callback isn't a proper place to check whether a state was updated, this is what second callback is for.
这篇关于this.setState 是否在反应中返回承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!