this.setState是否在react中返回promise [英] Does this.setState return promise in react

查看:207
本文介绍了this.setState是否在react中返回promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 componentWillMount() async。现在我可以使用 await setState

I made my componentWillMount() async. Now I can using await with the setState.

以下是示例代码:

componentWillMount = async() => {
  const { location, fetchRooms } = this.props
  await this.setState({ roomId: room && room.roomId ? room.roomId : 0 })
  fetchRooms()
}

所以这里的问题是 this.setState 返回promise,因为我可以使用 await 吗?

So question here is this.setState returns promise because I can use await with it?

编辑

Edit

当我等待它然后按顺序运行 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 { location, fetchRooms } = this.props
    console.log(1)
    await this.setState({ roomId: room && room.roomId ? room.roomId : 0 } => {
      console.log(2)
    })
    console.log(3)
    fetchRooms()
  }


推荐答案

setState 通常不是与承诺一起使用,因为很少有这样的需要。如果在状态更新( 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 可以按照此答案的建议进行宣传。

In order to return a promise, setState can be promisified, as suggested in this answer.

已发布的代码适用于 await ,因为它是一个黑客攻击。 await ... Promise.resolve(...)。然后(...)的语法糖。 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是否在react中返回promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆