我是 React-Native 新手
我有fetch
,通过它我获取了一些数据。我想做的是在请求结束并且数据准备好后调用另一个函数或更新状态。这是我的代码。
getProducts()
{
return fetch(prodUrl, {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
this.setState({brandList: responseData.products});
console.log("Brands State -> : ",this.state.brandList)
})
.done();
}
我在 componentWillMount()
中调用此 getProducts()
函数,并尝试在 render()
中使用获取的数据。
设置状态后,当我尝试 console.log()
时,我看不到变化,很可能是因为 fetch()
是异步的。如何在 fetch()
结束之前停止执行 render()
函数?或者您可以推荐任何其他请求类型,而不是同步的 fetch()
。
最佳答案
这并不是因为 fetch 是异步的,此时您已经拥有了 responseData。这是因为 setState 不会立即更改状态,因此在更改状态之前会调用 console.log 。 setState 有一个可选的回调,因为它是第二个参数,一旦 set 更新完成,就会调用该回调,因此您可以像这样更改它以正确查看效果:
getProducts()
{
return fetch(prodUrl, {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
this.setState(
{brandList: responseData.products},
() => console.log("Brands State -> : ",this.state.brandList)
);
});
}
关于javascript - react-native - 当获取结束时调用另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42484829/