Javascript 在axios.get()中设置类数据。然后()对数据没有影响
我有以下ES6代码:Javascript 在axios.get()中设置类数据。然后()对数据没有影响,javascript,ecmascript-6,this,arrow-functions,Javascript,Ecmascript 6,This,Arrow Functions,我有以下ES6代码: export default class HomePage extends Component { constructor(props) { super(props); this.state = { itemsWithData: [] }; this.details = [1, 2, 3] ; } loadDetails = items => { items.forEach(item => {
export default class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
itemsWithData: []
};
this.details = [1, 2, 3] ;
}
loadDetails = items => {
items.forEach(item => {
axios
.get(item.url)
.then(response => {
this.details = response.data;
})
.catch(e => {
console.warn(`Error while getting ${item.name} details`);
});
});
console.log(this.details);//It prints [1,2,3]
};
}
如您所见,我正在设置this.details
insidethen
。我已经将this.details
insidethen
记录下来,以确保它看到了类上下文。确实如此。但不知何故,设置细节在功能端似乎没有效果。它打印旧值。从请求返回的响应每次都有绝对不同的数据。所以它从来不是[1,2,3]。我应该怎么做才能适当地更改详细信息数据?这与异步等待有关吗
另外,实际上,传递给然后的箭头函数的内容如下:
this.details[item.name]=response.data;
因此,我并不是愚蠢地在每次转弯时都将细节设置为一个新值。箭头函数没有这个
,所以您需要使用oldskool函数(){}
instead@bdbdbd不,这很好,他想从父类继承这个范围,在这个例子中他做得很好。我知道他们没有。但我也知道它们指的是最外面的非箭头函数上下文。不是吗?这与箭头函数引用错误的上下文无关。问题是它们在错误的时间运行——在您记录旧值之后异步运行;this.details=response.data代码>但还是没用。cource的I使out arrow函数(forEach函数的函数)异步。