首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Axios React不追加信息获取请求

Axios React不追加信息获取请求
EN

Stack Overflow用户
提问于 2016-11-18 17:08:53
回答 1查看 957关注 0票数 1

我已经在Stack上找了一段时间了,但我想不出解决办法。

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

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

代码语言:javascript
复制
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检索信息的时候,还没有定义。

知道吗??可以随意尝试这个例子,只需调用此方法来检查它。

编辑

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2016-11-18 17:21:59

当您使用get发出axios请求时,您调用的是创建承诺对象的东西,该对象表示已发出的异步请求的状态。这可能是一个失败的响应,一个已解决的(成功的)响应,或者挂起的

您在获取正确状态时遇到问题的原因是在调用get调用之后立即记录数据,此时,inf.description不是您所期望的,而是状态为“待定”的承诺对象。

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

代码语言:javascript
复制
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>
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40682542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档