Promise.all() 和 setState() 反应本机
Promise.all() and setState() react-native
在一个组件中,我想使用 fetch API 从我的数据库中获取一些数据。获取所有数据后,我想使用 Promise.all() 更改组件的状态:
await Promise.all(data).then(
this.setState({
isLoading: false
})
)
我的问题是 setState() 在承诺解决之前触发。但是这段代码有效但是 isLoading 是一个数组而不是布尔值:
this.setState({
isLoading: await Promise.all(data)
})
有谁知道为什么?我是 React-Native 的新手,所以会喜欢一些输入!
then(
this.setState(...)
)
您正在立即调用 setState()
并将其结果传递给 then()
(就像任何其他函数调用一样)。
您需要将调用 setState
.
的函数或 lambda 传递给 then()
你应该这样改:
await Promise.all(data).then((result) => {
this.setState({
isLoading: false
})
}
)
基本上 .then
有一个函数作为参数,所以你必须把你的 setState
放在箭头函数中。
因为您正在使用 async
/await
,您根本不应该调用 then
。如果你仍然想使用它,你需要传递一个回调;但您的代码实际上应该如下所示:
await Promise.all(data);
this.setState({
isLoading: false
});
在一个组件中,我想使用 fetch API 从我的数据库中获取一些数据。获取所有数据后,我想使用 Promise.all() 更改组件的状态:
await Promise.all(data).then(
this.setState({
isLoading: false
})
)
我的问题是 setState() 在承诺解决之前触发。但是这段代码有效但是 isLoading 是一个数组而不是布尔值:
this.setState({
isLoading: await Promise.all(data)
})
有谁知道为什么?我是 React-Native 的新手,所以会喜欢一些输入!
then(
this.setState(...)
)
您正在立即调用 setState()
并将其结果传递给 then()
(就像任何其他函数调用一样)。
您需要将调用 setState
.
then()
你应该这样改:
await Promise.all(data).then((result) => {
this.setState({
isLoading: false
})
}
)
基本上 .then
有一个函数作为参数,所以你必须把你的 setState
放在箭头函数中。
因为您正在使用 async
/await
,您根本不应该调用 then
。如果你仍然想使用它,你需要传递一个回调;但您的代码实际上应该如下所示:
await Promise.all(data);
this.setState({
isLoading: false
});