react-native - 当fetch结束时调用另一个函数

时间:2017-02-27 11:37:25

标签: javascript asynchronous react-native request fetch

我是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();
    }

我在getProducts()中调用此componentWillMount()函数并尝试在render()中使用获取的数据。 设置状态后,当我尝试console.log()时,我看不到更改,很可能是因为fetch()是异步的。如何在render()结束之前停止执行fetch()功能?或者您可以推荐任何其他请求类型,而不是fetch()同步。

2 个答案:

答案 0 :(得分:2)

这不是因为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)
                );  
            });
    }

答案 1 :(得分:1)

你不想"停止"正在执行的render()函数。但是,如果数据可用,您可以应用检查渲染,并在不存在的情况下渲染微调器或其他内容。

非常粗略地描述了它的外观:

render() {
  let component = this.state.brandList ? <ComponentWithData/> : <Spinner/>;
  return component;
}