【问题标题】:how to properly replace axios api with fetch api and map over the received data in nodeJS?如何用 fetch api 正确替换 axios api 并映射 nodeJS 中接收到的数据?
【发布时间】:2021-07-13 17:57:18
【问题描述】:

这是整个文件的链接 - 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, users: [], error: '' }
{
  loading: false,
  users: [],
  error: 'res.json(...).map is not a function'
}

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

【问题讨论】:

  • res.json() 返回一个 Promise
  • 是的。如何处理?

标签: node.js reactjs redux fetch-api node-fetch


【解决方案1】:

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

【讨论】:

  • 它成功了。谢谢。我不知道第二个街区
猜你喜欢
  • 2020-10-28
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 2021-12-02
  • 2021-11-30
  • 2022-08-17
  • 1970-01-01
  • 2018-01-31
相关资源
最近更新 更多