json - 如何在 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;
}
解决方案
这是你想要的吗?
- 之后我删除了反斜杠
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>
);
}
推荐阅读
- c++ - 为什么我不能将函数分配给函数指针?
- arrays - C 中的 OpenMP 共享数组:减少与原子更新问题
- ios - 使用 UIPageViewController 时是否必须将 UIViewControllers 数组声明为惰性 var?
- python - 如何在当前页面显示结果?姜戈,阿贾克斯
- vim - 如何在 vim 中快速导航函数 arg 列表
- python - 如何在数据透视表中查找列的位置
- javascript - 不是在 JavaScript 中手动循环遍历 JSON 中的每个数组
- python - 在我的 pygame 项目中不断收到属性错误,我不明白为什么
- javascript - IE11 延迟渲染直到鼠标悬停或鼠标点击 React
- javascript - 击中敌人时的击中功能使所有子弹消失