我已经在Stack上找了一段时间了,但我想不出解决办法。
我有一个被调用的方法应该用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;发布于 2016-11-18 17:21:59
当您使用get发出axios请求时,您调用的是创建承诺对象的东西,该对象表示已发出的异步请求的状态。这可能是一个失败的响应,一个已解决的(成功的)响应,或者挂起的。
您在获取正确状态时遇到问题的原因是在调用get调用之后立即记录数据,此时,inf.description不是您所期望的,而是状态为“待定”的承诺对象。
以下是为您提出的解决方案:
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>
}
}https://stackoverflow.com/questions/40682542
复制相似问题