Javascript react native-在提取结束时调用另一个函数
我是新来的 我有Javascript react native-在提取结束时调用另一个函数,javascript,asynchronous,react-native,request,fetch,Javascript,Asynchronous,React Native,Request,Fetch,我是新来的 我有fetch,通过它我可以得到一些数据。我想做的是在请求结束且数据准备就绪后调用另一个函数或更新状态。这是我的密码 getProducts() { return fetch(prodUrl, {method: "GET"}) .then((response) => response.json()) .then((responseData) => { this.setS
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()
。您不想“停止”执行render()
函数。但是,如果数据可用,则可以应用检入渲染,并在数据不可用时渲染微调器或其他对象
非常粗略地描述了这可能是什么样子:
render() {
let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
return component;
}
render(){
让组件=this.state.brandList?:;
返回组件;
}
您不想“停止”执行render()
函数。但是,如果数据可用,则可以应用检入渲染,并在数据不可用时渲染微调器或其他对象
非常粗略地描述了这可能是什么样子:
render() {
let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
return component;
}
render(){
让组件=this.state.brandList?:;
返回组件;
}
这并不是因为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)
);
});
}
这并不是因为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)
);
});
}