2

In a component I would like fetch some data from my database using fetch API. When all the data is fetched I would like to change the state of the component using Promise.all():

await Promise.all(data).then(
  this.setState({
    isLoading: false
  })
)

My problem is that setState() fires before the Promises are resolved. However this code works but then isLoading is an array instead of boolean:

this.setState({
  isLoading: await Promise.all(data)
})

Does anyone know why? I'm kinda new to React-Native so would love some input!

4

3 回答 3

3

当您使用async/await时,您根本不应该打电话then。如果你仍然想使用它,你需要传递一个回调;但是您的代码实际上应该如下所示:

await Promise.all(data);
this.setState({
  isLoading: false
});
于 2016-09-05T20:05:13.553 回答
2

你应该这样改变:

await Promise.all(data).then((result) => {
   this.setState({
     isLoading: false
   })
 }
)

基本上.then有一个函数作为参数,所以你必须把你setState放在一个箭头函数里面。

于 2016-09-05T19:39:25.020 回答
0
then(
  this.setState(...)
)

setState() 立即调用并将其结果传递给then()(就像任何其他函数调用一样)。

您需要将函数或 lambda 传递给then()该调用setState

于 2016-09-05T19:38:17.027 回答