javascript this.setState 是否在反应中返回承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53409325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:10:58  来源:igfitidea点击:

Does this.setState return promise in react

javascriptreactjspromiseasync-awaitsetstate

提问by Profer

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

我做了我的componentWillMount()异步。现在,我可以用awaitsetState

Here is the sample code:

这是示例代码:

componentWillMount = async() => {
  const { fetchRooms } = this.props
  await this.setState({ })
  fetchRooms()
}

So question here is this.setStatereturns promise because I can use awaitwith it?

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

Edit

编辑

When I put await then it runs in a sequence 1, 2, 3And when I remove await then it runs 1, 3, 2??

当我放置 await 然后它按顺序运行1, 2, 3当我删除 await 然后它运行1, 3, 2??

  componentWillMount = async() => {
    const { fetchRooms } = this.props
    console.log(1)
    await this.setState({ } => {
      console.log(2)
    })
    console.log(3)
    fetchRooms()
  }

采纳答案by Estus Flask

setStateis 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通常不与承诺一起使用,因为很少有这样的需要。如果在 state update ( fetchRooms)之后调用的方法依赖于更新的 state ( roomId),它可以通过另一种方式访问​​它,例如作为参数。

setStateuses 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, setStatecan be promisified, as suggested in this answer.

为了返回一个promise,setState可以promisified,如this answer中所建议的。

Posted code works with awaitbecause it's a hack. await ...is syntactic sugar for Promise.resolve(...).then(...). awaitproduces 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:

发布的代码可以使用,await因为它是一个 hack。await ...是 的语法糖Promise.resolve(...).then(...)await产生一个滴答延迟,允许在状态更新完成后评估下一行,这允许按预期顺序评估代码。这与:

this.setState({ roomId: room && room.roomId ? room.roomId : 0 } => {
  console.log(2)
})

setTimeout(() => {
  console.log(3)
});

There's no guarantee that the order will stay same under different conditions. Also, first setStatecallback isn't a proper place to check whether a state was updated, this is what second callback is for.

无法保证订单在不同条件下会保持不变。此外,第一个setState回调不是检查状态是否更新的合适位置,这就是第二个回调的用途。

回答by alki

You can promisify this.setStateso that you can use the React API as a promise. This is how I got it to work:

您可以承诺,this.setState以便您可以使用 React API 作为承诺。这就是我让它工作的方式:

class LyricsGrid extends Component {

  setAsyncState = (newState) =>
    new Promise((resolve) => this.setState(newState, resolve));

Later, I call this.setAsyncStateusing the standard Promise API:

后来,我this.setAsyncState使用标准的 Promise API 调用:

this.setAsyncState({ lyricsCorpus, matrix, count })
  .then(foo1)
  .then(foo2)
  .catch(err => console.error(err))

回答by Tazo leladze

setState does not return a promise.

setState 不返回承诺。

setState has a callback.

setState 有一个回调。

this.setState({
    ...this.state,
    key: value,
}, () => {
    //finished
});

回答by Quentin

It does not return a promise.

它不返回承诺。

You can slap the awaitkeyword in front of any expression. It has no effect if that expression doesn't evaluate to a promise.

您可以将await关键字放在任何表达式之前。如果该表达式不计算为承诺,则无效。

setStateaccepts a callback.

setState接受回调。

回答by mvofreire

You can simple customize a Promise for setState

您可以简单地为 setState 自定义一个 Promise

  componentWillMount = async () => {
    console.log(1);
    await this.setRooms();
    console.log(3);
  };

  setRooms = () => {
    const { fetchRooms } = this.props;
    return fetchRooms().then(({ room }) => {
      this.setState({ roomId: room && room.roomId ? room.roomId : 0 }, _ =>
        console.log(2)
      );
    });
  };

Or

或者

  setRooms = async () => {
    const { fetchRooms } = this.props;
    const { room } = await fetchRooms();

    return new Promise(resolve => {
      this.setState({ roomId: room && room.roomId ? room.roomId : 0 }, _ =>
        resolve()
      );
    });
  };

Hope this help =D

希望这有帮助 =D

回答by Bogdan Manole

Don't think setStateis returning a Promisebut you can always do this

不要认为setState是返回 aPromise但你总是可以做到这一点

 await new Promise( ( resolve ) => 
     this.setState( {
         data:null,
     }, resolve )
 )

or you can make some utility function like this

或者你可以做一些这样的实用功能

const setStateAsync = ( obj, state ) => {
    return new Promise( ( resolve ) =>
        obj.setState( state , resolve )
    )
}

and use it inside a React.Component like this:

并在 React.Component 中使用它,如下所示:

await setStateAsync(this,{some:'any'})