react-native - 获取结束时调用另一个函数
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()
。
您不想"stop" render()
函数被执行。但是,如果数据可用,您可以在渲染中应用检查,并在数据不可用时渲染微调器或其他东西。
这可能是什么样子的非常粗略的草图:
render() {
let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
return component;
}
这不是因为 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)
);
});
}
我是 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()
。
您不想"stop" render()
函数被执行。但是,如果数据可用,您可以在渲染中应用检查,并在数据不可用时渲染微调器或其他东西。
这可能是什么样子的非常粗略的草图:
render() {
let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
return component;
}
这不是因为 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)
);
});
}