[英]react-native - call another function when fetch is over
我是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有一个可选的回调,因为它是第二个参数,一旦完成设置更新,将调用它,因此您可以像这样更改它以正确查看效果:
getProducts()
{
return fetch(prodUrl, {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
this.setState(
{brandList: responseData.products},
() => console.log("Brands State -> : ",this.state.brandList)
);
});
}
您不想“停止” render()
函数的执行。 但是,您可以在数据可用的情况下应用检入渲染,并在微调器或其他数据不可用时进行渲染。
关于它的外观非常粗略:
render() {
let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
return component;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.