Axios React不附加信息获取请求

时间:2016-11-18 17:08:53

标签: javascript reactjs hash axios

我一直在堆栈上寻找一段时间,但我无法找到解决方案。

我有一个被调用的方法应该使用Axios执行GET请求。

在方法的开头我创建了一个新的哈希,所以我想在那里存储所有信息然后只返回那个哈希。

import React, {Component} from "react";
import axios from 'axios';
class Json extends Component{
  getInformation(){
    let inf = {};
     axios
      .get("http://codepen.io/jobs.json")
      .then(result=> {
        inf.description = result.data.jobs[0].description;

      })
      .catch(err=>{
        console.log("STH WRONG");
      });

      console.log(inf);
    return(inf);
  }

那么我的问题是什么?如果我检查inf变量内部是什么,它就是空的。但是,如果我使用Chrome检查,在控制台上我看到它是空的,但是当我查看详细信息时,键和值就在那里。目前我正在尝试使用inf.description检索信息未定义。

任何想法?请随意尝试此示例,只需调用此方法进行检查即可。

修改

import React, {Component} from 'react';
import axios from 'axios';
class Json extends Component{
  constructor(props){
    super(props);
    this.state={title: ""};

  }
  getInformation(){
    let inf = {};

    // .get("/data/CA_data.json")
     axios
      .get("http://codepen.io/jobs.json")
      .then(result=> {
        inf.description = result.data.jobs[0].description;

      })
      .catch(err=>{
        console.log("STH WRONG");
      });

      console.log(inf);
    return(inf);
  }

  render(){
    let inf = this.getInformation();

    return(
      <h1>

      </h1>
    );
  }
}


export default Json;

1 个答案:

答案 0 :(得分:1)

当您使用get发出axios请求时,您正在调用创建Promise对象的内容,该对象表示所做异步请求的状态。这可能是失败的回复,已解决的(成功)回复,或 待定

您在获取正确状态时遇到问题的原因是您在调用get电话后立即记录了数据,此时inf.description不是您所期望的那样但很可能是状态为“待定”的Promise对象。

以下是为您提出的解决方案:

import React, {Component} from "react";
import axios from 'axios';
class Json extends Component{
  constructor(props){
    super(props);
    this.state = { inf: {} }
  }
  componentDidMount(){
    this.getInformation();  // make the axios call in this lifecycle method
  }
  getInformation(){
    return axios
      .get("http://codepen.io/jobs.json")
      .then(result=> {
        this.setState({ inf.description: result.data.jobs[0].description });
        // this.state.inf.description is available here because
        // then() gets called once the promise has been resolved

        // the call to this.setState causes a re-render of this component
      })
      .catch(err=>{
        console.log("STH WRONG");
      });
  }
  render(){
    // this header will initially show the initial value of description
    // once the PROMISE from the getInformation call within 
    // componentDidMount resolves and calls this.setState, 
    // this component will re-render with the updated state value(s)

    <div>{ this.state.inf.description }</div>
  }
}