JavaScript数据解构

时间:2019-04-10 09:04:06

标签: javascript

我试图抓住破坏的概念。我知道这是一种将值分配给对象或数组中的变量的方法。我有通过这种方式从API获取的数据

const getAUserProfile = () => {
  const api = "https://randomuser.me/api/";

  const data = fetch(api).then(response => {
    return response.json();
  });

  console.log(data);
  displayUserPhotoAndName(data);
};

console.log结果显示了这一点 enter image description here

在displayUserPhotoAndName函数中,我试图像这样破坏数据

const displayUserPhotoAndName = data => {
    const {results} = data;
    console.log(results);
};

但是console.log(results)返回未定义。显然我似乎没有正确地破坏数据,或者我的提取方法不正确,这是我的想法。请问在这种情况下解构数据的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

尝试

fetch(api )
  .then((resp) => resp.json()) // Transform the data into json
  .then(function(data) {
       displayUserPhotoAndName(data);
    })
  })