我正在使用axios进行get请求。我确定当我发出get请求时,我会得到正确的数据。
在我的构造函数中有一个数组(allQuotes)。然而,当我尝试在componentDidMount中引用它时,它是未定义的。
class App extends Component {
constructor() {
super();
this.allQuotes = [];
}
componentDidMount() {
axios.get("http://getquote.herokuapp.com/get")
.then(function (response) {
this.allQuotes = response.data;
console.log(response.data);
this.getNewQuote();
})
.catch(function (error) {
console.log("Error: ", error);
//console.dir(error);
});
}
运行后,控制台提示“无法将属性'allQuotes'设置为未定义”。
为什么this
是未定义的呢?
then()
内部的this
不是父函数的this
,你需要绑定它,在传递给then()
的函数末尾添加.bind(this)
。 - LuisEgan