提问者:小点点

如何正确地用fetch api替换axios api,并在NodeJS中映射接收到的数据?


这是整个文件的链接-asyncactions.js。

带有axios api的部分-

const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRrequest());
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        // res.data is the array of users
        const users = res.data.map((user) => user.id);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        // error.message gives the description of message
        dispatch(fetchUsersFaliure(error.message));
      });
  };
};

函数输出-

{ loading: true, users: [], error: '' }
{
  loading: false,
  users: [
    1, 2, 3, 4,  5,
    6, 7, 8, 9, 10
  ],
  error: ''
}

用提取api替换零件-

    const fetchUsers = () => {
  return function (dispatch) {
    dispatch(fetchUsersRrequest());
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        const users = res.json().map((user) => user.id);
        console.log(users);
        dispatch(fetchUsersSuccess(users));
      })
      .catch((error) => {
        dispatch(fetchUsersFaliure(error.message));
      });
  };
};

输出-

{ loading: true, users: [], error: '' }
{
  loading: false,
  users: [],
  error: 'res.json(...).map is not a function'
}

我做错了什么?为什么我不能在数据上映射?


共1个答案

匿名用户

调用res.json()将返回一个承诺。您需要添加一个second then块:

fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((res) => {
   const users = res.map((user) => user.id);
   console.log(users);
   dispatch(fetchUsersSuccess(users));
 })
.catch((error) => {
   dispatch(fetchUsersFaliure(error.message));
});