当前位置: 首页 > 知识库问答 >
问题:

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

陶超
2023-03-14

这是整个文件的链接-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个答案

何楷
2023-03-14

调用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));
});
 类似资料:
  • 本文向大家介绍如何正确使用Nodejs 的 c++ module 链接到 OpenSSL,包括了如何正确使用Nodejs 的 c++ module 链接到 OpenSSL的使用技巧和注意事项,需要的朋友参考一下 事情的起因是这样的, 因为某些原因, 最近在写 Nodejs 的 c++ module, 然后在js这边调用。  网络通信自然离不开ssl, 于是需要链接到Openssl的库。 我们本来的

  • 仅供参考:我已经删除了所有apache默认的webapp文件,并启动了我自己的项目,因此可以使用访问它,这很好。 我在驱动器中的servlet位置: 我在eclipse IDE中的包:eclipse IDE映像中的包 和我的web.xml文件: 我的HTML表单: 感谢所有的回复:)

  • 问题内容: 我想将创建的JSON文件转换为SQLite数据库。 我的意图是稍后决定最好的数据容器和入口点是json(通过文本编辑器输入数据)或SQLite(通过类似电子表格的GUI(例如SQLiteStudio)输入数据)。 我的json文件是这样的(包含我城市中某些十字路口的交通数据): 并且我用以下几行Python代码创建了具有一对多关系的漂亮数据库: 但是问题是,当我准备使用诸如的实际数据插

  • 问题内容: 我正在使用python-spidermonkey,它在内部使用PyMapping_Check来识别用作全局对象(在rt.new_context(global)中)是否实现了映射协议。(这基本上是传递给python- spidermonkey的字典,因此javascript对python变量的访问受到限制。) 我无法在Python中找到映射协议的正式定义,因此我一直在尝试和尝试确定其中的

  • 我有以下POJO,可以序列化为字节或。 当试图反序列化正文时,该错误似乎是从请求类生成的: 我怎样才能正确地反序列化地图?

  • 在RestEasy 3.0.16中,最终版本PreProcessInterceptor接口是不推荐的。那么这个接口的适当替换是什么。在jboss EAP7中,RestEasy Version3.0.16.final被使用。