[英]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.