【问题标题】:Is it possible to map through an array and fetch data from a server for each item gotten from the mapped array?是否可以通过数组进行映射并从服务器获取从映射数组中获取的每个项目的数据?
【发布时间】:2023-02-07 01:35:59
【问题描述】:

数据由数据库中不同用户发布的一系列帖子组成。每个帖子都包含发帖用户的 _id。我想映射每个帖子,获取帖子的 _id 并获取每个帖子的用户数据。这就是我取得的进展。有没有正确的方法或更好的方法?我遇到了错误。

    const getUsers = () => {
    data.map(async () => {
        await axios({
        method: "POST",
        withCredentials: true,  url:`https://droplikebackend.herokuapp.com/api/user/get/${id}`,
        data: {
            userId: data.userId,
        },
      })
        .then((res) => {
          console.log(res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    });
  };

【问题讨论】:

    标签: javascript reactjs arrays axios


    【解决方案1】:

    最好的方法是在单独的函数中提取确切的 getUser 逻辑。我不确定的是为什么方法是“POST”以及为什么用户的 id 在 axios 的 URL 和数据属性中。

    如您所见,不需要 .then 和 .catch,但如果您想捕获某些东西 - 只需使用普通的 try/catch 块,不要将 async/await 与 .then.catch 混合使用:

    const getUser = async (userId) => {
      const response = await axios({
        method: "POST",
        withCredentials: true,
        url: `https://droplikebackend.herokuapp.com/api/user/get/${userId}`,
        data: { userId: userId }
      });
      return response.data;
    };
    

    现在关于用法 - 如您所见,本例中的 map 函数将返回一个 Promises 数组,您可以使用 Promise.all() 方法等待它们并获得结果。如果它是一个带有等待的 for 循环,所有的 promise 都会模拟地触发,而不是一个一个地触发。缺点:如果你的 API 有速率限制器——你可能会被禁止一段时间,因为对于 100 个帖子,100 个 getUser 请求将在不到一秒内被触发。

    const getUsers = async () => {
      const uniqueUserIds = [...new Set(data.map((x) => x.userId))];
      const promises = uniqueUserIds.map(getUser);
      const users = await Promise.all(promises);
      return users;
    };
    

    【讨论】:

      【解决方案2】:

      应用程序.js

      const axios = require("axios");
      const getUsers = async (id) => {
        const data = await axios({
          method: "get",
          url: id // if exist id search for id, if not exist map of restult
            ? `https://jsonplaceholder.typicode.com/posts/${id}`
            : "https://jsonplaceholder.typicode.com/posts"
        });
      
        if (id) {
          // if exist an id return a object and not array
          return console.log(data.data.id);
        } else {
          // map the array
          data.data.map((post) => console.log(post.id));
        }
      };
      
      getUsers(); // all post
      // getUser(1) only bring the post with id 1
      

      您不能使用 data.map,因为之前未定义数据,您可以验证该函数是否带有 id 以及是否全部发布或仅发布一个帖子。 我使用 JsonPlaceHolder 因为你的 api 是一个帖子。但是是一样的。 在我的示例中,仅在 post 上查找和对象,您可以传递一个数组,并且如果是对象或数组则不需要验证帽子,并且 data.map 可以正常工作 您不能使用 data.map,因为之前未定义数据,您可以验证该函数是否带有 id 并全部发布或仅发布一个帖子。 我使用 JsonPlaceHolder 因为你的 api 是一个帖子。但是是一样的。 在我的示例中,仅在 post 上查找和对象,您可以传递一个数组,并且如果是对象或数组则不需要验证帽子,并且 data.map 可以正常工作

      【讨论】:

      • 不要同时使用 async await 和 then 。用代码保持秩序
      • 总之,如果您需要点击其中的帖子的信息,请传递帖子的 id。
      • 不确定这是否是有问题的问题,但无论如何,我会问一些关于你的代码的问题。如果我将 id = 0 传递给你的方法会发生什么?
      • 我已经添加了一个答案,请检查它。 @SergeySosunov
      【解决方案3】:
      [
          {
              "_id": "62f45046a763042f5f35ba06",
              "userId": "62eb470392306d95ed89d964",
              "Image": "",
              "caption": "Monday!",
              "likes": [],
              "comments": []
          },
          {
              "_id": "62f4504ea763042f5f35ba08",
              "userId": "62eb470392306d95ed89d964",
              "Image": "",
              "caption": "Tuesday!",
              "likes": [],
              "comments": []
          }
      ]
      

      这就是数据的样子。我想显示发布这些帖子的用户的用户名,我只能通过从附加到帖子的 userId 中获取他们的个人数据来做到这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-25
        • 2019-07-03
        • 2021-06-02
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        相关资源
        最近更新 更多