使用 react 钩子显示来自 jsonplaceholder api 的数据



我有简单的 rest api,我正在尝试显示来自 jsonplaceholder fake api 的用户

这是我的函数组件

import React, {useState, useEffect} from "react";
import axios from 'axios';
export default function TableList() {
const [data, setData] = useState({ hits: [] });
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://jsonplaceholder.typicode.com/users',
);
setData(result.data);
console.log(result.data);
};
fetchData();
}, []);

return (
<div>
<ul>
{data.hits.map(item => (
<li key={item.id}>
<h1>{item.name}</h1>
</li>
))}
</ul>
</div>
);
}

不幸的是,我收到以下错误:

TableList.js:22 Uncaught TypeError: Cannot read property 'map' of undefined

我的代码有什么问题?

您设置的数据不正确,您应该空检查data.hits。这是一个工作示例

function TableList() {
const [users, setUsers] = useState({ hits: [] });
useEffect(() => {
const fetchData = async () => {
const { data } = await axios(
"https://jsonplaceholder.typicode.com/users"
);
setUsers({ hits: data });
};
fetchData();
}, [setUsers]);
return (
<div>
<ul>
{users.hits &&
users.hits.map(item => (
<li key={item.id}>
<span>{item.name}</span>
</li>
))}
</ul>
</div>
);
}

https://codesandbox.io/s/affectionate-lehmann-17qhw

"hits" 是必要的吗?

import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function MiJSON(){
const [users, setUsers] = useState([]);
const urlJson= 'https://jsonplaceholder.typicode.com/users';
useEffect(()=>{
const fetchData = async ()=>{
const users_data = await axios(urlJson);
setUsers(users_data);
};
fetchData();
},[setUsers])
console.log(users)
return (
<div>
<h1>USERS</h1>
<ul>      
{(users.length !== 0)
?
users.data.map(item => (
<li key={item.id}>
<span>{item.name}</span>
</li>
))

: <h1>Sorry info not found</h1>
}
</ul>
</div>
)
}

相关内容

  • 没有找到相关文章