AJAX 上的获取和函数错误以及 API 调用 reactjs

Fetch and function error on AJAX and APIs call on reactjs

我在获取从 unsplash 托管的文件时收到 items.map is not a function 错误。

我不确定问题是来自 .map 还是来自从源获取文件。

下面是我的代码,也是完整的沙盒代码 https://codesandbox.io/

import { React, useState, useEffect } from "react";

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map((item) =>
          <li key={item.results.id}>
            {item.results.description}
          </li>
        )}
      </ul>
    );
  }
}

export default MyComponent;

似乎响应 JSON 是一个对象而不是数组。当您使用对象更新 items 状态时,它不再是可映射的。

// 20220209004834
// https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U#f3f3f3

{
  "total": 10000,
  "total_pages": 1000,
  "results": [
    {
      "id": "_LuLiJc1cdo",
      "created_at": "2016-06-06T01:08:36-04:00",
      "updated_at": "2022-02-08T13:00:46-05:00",
      "promoted_at": "2016-06-06T01:08:36-04:00",
      ...
      "description": "follow @kalenemsley on ig",
      ...
    },
    ...
  ],
  ...
}

您可能需要 results 数组 属性 代表您所在的州。

useEffect(() => {
  fetch("....")
    .then((res) => res.json())
    .then(
      (result) => {
        setIsLoaded(true);
        setItems(result.results);
      },
      (error) => {
        setIsLoaded(true);
        setError(error);
      }
    );
}, []);

然后 映射每个项目时您正确访问属性

<ul>
  {items.map((item) =>
    <li key={item.id}>
      {item.description}
    </li>
  )}
</ul>