【问题标题】:Axios returning empty array before returning the dataaxios在返回数据之前返回空数组
【发布时间】:2019-12-16 17:46:48
【问题描述】:

我有一个简单的反应应用程序,它从 API 中提取数据并将其打印到控制台。 我正在使用 Axios 从 API 获取值。 这是 API:https://mobile-tha-server-8ba57.firebaseapp.com/walmartproducts/1/20

import React, { Component } from 'react';
import axios from 'axios';

class Products extends Component {
    state = {
        MetaProducts: []
    }
    async componentDidMount(){
        const res = await axios.get('https://mobile-tha-server-8ba57.firebaseapp.com/walmartproducts/1/20')
        this.setState({ MetaProducts: res.data.products});
    }

    render() {
        console.log(this.state.MetaProducts);
        return(
            <div>
                Products
            </div>

        )
    }
}


export default Products;

但是axios,先返回一个空数组,然后返回带有数据的数组。

控制台:
Products.js:14 []
Products.js:14 (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, { …}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}]

【问题讨论】:

    标签: javascript reactjs rest api axios


    【解决方案1】:

    这是因为反应生命周期的异步行为。您的渲染在您的 axios 请求完成之前被调用,并且 this.state.Metaproducts 从未在渲染内部更新,因为它已经在您的请求之前渲染。 您可以等待来自axios的回调,然后再更新状态,并确保在ajax完成后渲染产品

    我又添加了一个状态变量init,并在得到服务器响应后将其设置为true。默认情况下init 将为 false,然后您可以显示“加载消息”。

    希望对你有帮助

    import React, { Component } from 'react';
    import axios from 'axios';
    
    class Products extends Component {
      state = {
        MetaProducts: [],
        init:0,
      }
    
      async componentDidMount() {
       await axios.get('https://mobile-tha-server-8ba57.firebaseapp.com/walmartproducts/1/20').then(res => {
          this.setState({ MetaProducts: res.data.products, init:1 });
        });
      }
    
      renderProduct() {
        return <ul>
        {this.state.MetaProducts.map(p =>
          <li>
            {p.productName}
          </li>
        )};
        </ul>;
      }
    
      render() {
        return this.state.init ? <div>{this.renderProduct()}</div> : <div>loading...</div>;
       }
    }
    
    
    
    export default Products;
    

    【讨论】:

    • 这真的很有帮助,谢谢。我还试图弄清楚如何绘制对象。顺便说一句,你还没有声明“res”
    【解决方案2】:

    您的意思是控制台上的空数组吗?当然。它将打印空数组。你必须看看反应生命周期。 Render 将首先运行,然后是 componentDidMount。因为您将MetaProducts 初始化为一个空数组,所以它会首先打印并清空数组。

    【讨论】:

      【解决方案3】:

      这是因为在 React 中 componentDidMount 是在 render 方法之后调用的。

      在此处查看 React 生命周期方法 https://reactjs.org/docs/react-component.html#mounting

      它首先记录空数组,这是默认状态,然后是 axios api 调用返回的任何内容。

      【讨论】:

        猜你喜欢
        • 2020-08-15
        • 1970-01-01
        • 1970-01-01
        • 2017-05-18
        • 2017-11-23
        • 1970-01-01
        • 2021-10-04
        • 2020-07-07
        • 2019-10-10
        相关资源
        最近更新 更多