将响应数据传递到数组

时间:2020-11-06 15:12:18

标签: javascript

如何将获取的数据传递给称为用户的数组?我试过使用this.users = data.data,然后使用console.log(users),但没有任何显示。

我也在尝试映射响应,我在控制台Uncaught TypeError: fetchData.map is not a function中遇到错误

const users = [];

const fetchData = () => {
    axios.get('https://reqres.in/api/users')
  .then(({data}) => {
    this.users = data.data;
    console.log(data);
  })
}
fetchData();

const mapUsers = fetchData.map((item) => {
    return {
        avatar: item.avatar
    }
})

1 个答案:

答案 0 :(得分:1)

也许您需要将地图移到回调中

let users = [];

const fetchData = () => {
  axios.get("https://reqres.in/api/users").then(({ data }) => {
    users = data.data;

    const mapUsers = users.map((item) => {
      return {
        avatar: item.avatar,
      };
    });
    console.log("mapUsers", mapUsers);
  });
};

fetchData();

let users = [];

const fetchData = () => {
  return axios.get("https://reqres.in/api/users").then(({ data }) => {
    return data.data;
  });
};

fetchData().then((data) => {
  console.log(data);
  const mapUsers = data.map((item) => {
    return {
      avatar: item.avatar,
    };
  });

  console.log("mapUsers", mapUsers);
});