React组件方法返回空数组

时间:2016-10-27 16:19:58

标签: javascript html5 reactjs console.log babel

对于我正在研究的项目,我编写了两个用于从REST API请求和解析数据的反应方法。但是,应该保存已解析数据的数组始终返回空。我不确定为什么会这样。任何帮助表示赞赏。

React获取和解析数据的方法:

[
 [
  {
   first_name: "First Name Here...", 
   last_name: "Last Name Here...",
   full_name: "Full Name Here",
   date: "2016-01-17",
   charges: {
       cosmetic: 25000.00,
       medical: 25000.00,
       total: 50000.00
   },
   payments: 75000.00,
   appointments: 99,
   pk: 5
  }, 
  {
   first_name: "First Name Here...", 
   last_name: "Last Name Here...",
   full_name: "Full Name Here",
   date: "2016-01-24",
   charges: {
       cosmetic: 25000.00,
       medical: 25000.00,
       total: 50000.00
   },
   payments: 75000.00,
   appointments: 99,
   pk: 5
  }, 
 ],
 [
  {
   first_name: "First Name Here...", 
   last_name: "Last Name Here...",
   full_name: "Full Name Here",
   date: "2016-01-17",
   charges: {
       cosmetic: 25000.00,
       medical: 25000.00,
       total: 50000.00
   },
   payments: 75000.00,
   appointments: 99,
   pk: 5
  }, 
  {
   first_name: "First Name Here...", 
   last_name: "Last Name Here...",
   full_name: "Full Name Here",
   date: "2016-01-24",
   charges: {
       cosmetic: 25000.00,
       medical: 25000.00,
       total: 50000.00
   },
   payments: 75000,
   appointments: 99,
   pk: 5
  },
 ]
];

来自Rest API的数据示例:

{{1}}

1 个答案:

答案 0 :(得分:2)

你遇到的问题是你正在进行异步的ajax调用和之后的设置状态。工作流程是:您使用axios进行api调用,链接到.then函数,该函数将在数据返回后执行,然后将该数据推送到您的数组中。实际的javascript工作流是这样的:你进行ajax调用,而不是等待响应返回javascript继续执行并运行你的setstate函数。在运行setState函数时,您的数据数组仍然为空,因为没有响应。

如果是我,我会考虑使用axios.all来获取一系列ajax调用,你可以将一个.then函数链接到该函数,并且一旦所有的api调用完成它就会运行。此时,您可以将所有数据推送到同一个.then块中的数据数组和setState。这将确保在数据实际返回后状态得到更新。

如果你查看这篇文章http://codeheaven.io/how-to-use-axios-as-your-http-client/#performing-multiple-requests-simultaneously,它会解释如何一次执行多个api调用

类似以下的东西应该有效,我没有机会测试,所以我要仔细检查它,但它应该做我正在谈论的事情

getData(){
    const { url, queries } = this.state;
    let data_arr = [];

    // map over queries, create array of axios promises
    const axiosQueries = queries.map(function(query) {
      let post_query = {
          full_name: query.name,
          date_start: query.startdate,
          date_end: query.enddate
      };
      return axios.post(url, post_query)
    });
  // set self to be equal to react component 
  var self = this; 

  // chain all axios promises and then give the results back as an array containing each request
   axios.all(axiosQueries).then(function(results){

   // go through each result and push it into data array
     results.forEach(function(response) {
       data_arr.push(response.data)
     })

     // once all data is processed set state to data array.
     return self.setState({data: data_arr});

   })

}