Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在axios.get()中设置类数据。然后()对数据没有影响_Javascript_Ecmascript 6_This_Arrow Functions - Fatal编程技术网

Javascript 在axios.get()中设置类数据。然后()对数据没有影响

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 => {

我有以下ES6代码:

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
inside
then
。我已经将
this.details
inside
then
记录下来,以确保它看到了类上下文。确实如此。但不知何故,设置细节在功能端似乎没有效果。它打印旧值。从请求返回的响应每次都有绝对不同的数据。所以它从来不是[1,2,3]。我应该怎么做才能适当地更改详细信息数据?这与异步等待有关吗

另外,实际上,传递给
然后
的箭头函数的内容如下:

this.details[item.name]=response.data;

因此,我并不是愚蠢地在每次转弯时都将细节设置为一个新值。

箭头函数没有
这个
,所以您需要使用oldskool
函数(){}
instead@bdbdbd不,这很好,他想从父类继承这个范围,在这个例子中他做得很好。我知道他们没有。但我也知道它们指的是最外面的非箭头函数上下文。不是吗?这与箭头函数引用错误的上下文无关。问题是它们在错误的时间运行——在您记录旧值之后异步运行;this.details=response.data但还是没用。cource的I使out arrow函数(forEach函数的函数)异步。