【问题标题】:Trying to return objects similar to mapping试图返回类似于映射的对象
【发布时间】:2020-08-19 19:41:05
【问题描述】:

我正在尝试返回一个对象列表,以便稍后在 ag-grid 中显示。但是我最初试图映射但注意到它不是一个数组,它只包含在 {} 中,因此得到了 not a function 错误。任何提示或相关资源的链接都将不胜感激,因为我找不到任何对我有帮助的东西

api 返回 {"author":"j.k rowling", "title":"Harry Potter", "id":"1", "pages":"1000"}

  useEffect(() => {
        fetch(http://fakeapi.com/)
            .then(res => res.json())
            .then(json => json.map(res => {
                return {
                    author: res.author,
                    title: res.title,
                    id: res.id,
                    pages: res.pages,
                };
            })
            ).then(res => setRowData(res));
    }, []);

【问题讨论】:

  • 你可以试试Object.values(json).map
  • 一直在尝试,但没有成功

标签: node.js reactjs fetch use-effect


【解决方案1】:

您从服务器获得的响应表明您没有获得数组,而是获得了 1 个艺术家。您需要让您的服务器返回一系列书籍信息。所以你的 JSON 响应是:

[
    {
      "id":"1",
      "author": "j.k rowling",
      "title": "Harry Potter",
      "pages":"7000"
    },
    {
      "id":"2",
      "author": "a.k sayomh",
      "title": "Singer role",
      "pages":"10000"
    },
    //...
]

然后在您的 ag-grid 中,您可以像以前一样使用 .map 函数。

如果您没有获得一系列书籍信息,则该 API 不适用于您的用例。

假设数据总量为 1 时 API 返回一个对象,如果更多则返回一个数组。那你能做什么呢。

useEffect(() => {
  fetch(http://fakeapi.com/)
      .then(res => res.json())
      .then(json => Array.isArray(json)
        ? json.map(res => ({
            author: res.author,
            title: res.title,
            id: res.id,
            pages: res.pages,
          ))
        : [json]
      ).then(res => setRowData(res));
}, []);

【讨论】:

  • 是的,我知道我没有收到数组。我无法更改服务器,因此必须使用 {//...} 中的对象,并且知道这意味着我不能只映射它,但它的代码是我不知道的
  • 您到底想达到什么目标?你想买一堆书吗?如果是,您确定您发送的请求正确吗?
猜你喜欢
  • 1970-01-01
  • 2018-05-30
  • 2021-02-17
  • 1970-01-01
  • 2023-02-09
  • 2021-09-10
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多