首页 > 解决方案 > 如何在 React 中使用 useEffect 遍历 JSON 数组?

问题描述

我正在尝试使用 useEffect 遍历 JSON 数组。当我使用下面的代码(从 useState 中删除了数组)并指定了一个用户时,我能够获取数据。但是它不适用于整个阵列...任何建议将不胜感激。

function GitHubUser() {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch(`https://api.github.com/users/`)
      .then(res => res.json())
      .then(setData)
      .catch(console.error);
  }, []);

  if (data) {
    return (
      <div>
        <h1>{data.userId}</h1>
        <img src={data.avatar_url} width={100} alt={"github avatar"}/>
        <p>{data.login}</p>
      </div>
    );
  }
  return null;
}

标签: jsonreactjsuse-effect

解决方案


这是你想要的吗?

  • 之后我删除了反斜杠https://api.github.com/users*here*
  • 我在 useEffect 挂钩中设置了数据,在您的示例中您没有这样做。
  • 并将数组映射到数据中,它显示所有 github 用户的图像和名称。

.

function GitHubUser() {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch(`https://api.github.com/users`) // removed the backslash here
      .then(res => res.json())
      .then(data => setData(data)) // changed this line
      .catch(console.error);
  }, []);

  console.log(data)


    return (
      <div>
        {data.map((item, key) => <> // Mapping through the array here
        <h1 key={key}>{item.id}</h1>
        <img src={item.avatar_url} width={100} alt={"github avatar"}/>
        <p>{item.login}</p>
        </>
        )}
      </div>
    );
  }

推荐阅读