【问题标题】:react-native - call another function when fetch is overreact-native - 提取结束时调用另一个函数
【发布时间】:2017-02-27 11:37:25
【问题描述】:

我是 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() 同步。

【问题讨论】:

    标签: javascript asynchronous react-native request fetch


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您不想“停止”render() 函数的执行。但是,如果数据可用,您可以应用检入渲染,并在数据不可用时渲染微调器或其他东西。

      大概的样子:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 1970-01-01
        相关资源
        最近更新 更多