如何使用 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: ''
}

用fetch 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,error: 'res.json(...).map is not a function'
}

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

解决方法

调用 res.json() 将返回一个 Promise。您需要添加第二个然后阻止:

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));
});