英文:
Why is `data.map()` function not working as expected when used with data fetched from an API?
问题
无法解决这个问题。
尝试过 {data?.map(person=>{...}
和 {data && data.map(person=>{...}
。
似乎 data
是一个空数组。
尝试过 {data?.map(person=>{...}
和 {data && data.map(person=>{...}
,如何解决?数据数组似乎是空的,但如何从 API 中添加数据到数组中。
英文:
Unable to fix this issue.
Tried {data?.map(person=>{...}
and {data && data.map(person=>{...}
import {useState} from 'react';
const App = () => {
const [data, setData] = useState({data: []});
const [isLoading, setIsLoading] = useState(false);
const [err, setErr] = useState('');
const handleClick = async () => {
setIsLoading(true);
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'GET',
headers: {
Accept: 'application/json',
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log('result is: ', JSON.stringify(result, null, 4));
setData(result);
} catch (err) {
setErr(err.message);
} finally {]
setIsLoading(false);
}
};
console.log(data);
return (
<div>
{err && <h2>{err}</h2>}
<button onClick={handleClick}>Fetch data</button>
{isLoading && <h2>Loading...</h2>}
{data && data.map((person) => {
return (
<div key={person.id}>
<h2>{person.title}</h2>
<h2>{person.userId}</h2>
<br />
</div>
);
})}
</div>
);
};
export default App;
Seems like its an empty array in data.
Tried {data?.map(person=>{...}
and {data && data.map(person=>{...}
how to fix this? Data array feels like empty but how to add data into array from API.
答案1
得分: 1
我检查了端点,它不是一个数组,map
函数只适用于数组。如果您将端点更改为获取所有帖子 https://jsonplaceholder.typicode.com/posts
,它将按预期工作
如果您需要显示帖子数据,使用 map
是完全没有意义的,您的组件应该返回这个:
return (
<div key={data.id}>
<h2>{data.title}</h2>
<h2>{data.userId}</h2>
<br />
</div>
);
英文:
I checked the endpoint and it is not an array, map function works only for arrays. If you change your endpoint to fetch all posts https://jsonplaceholder.typicode.com/posts
it is going to work as expected
If what you need is to display post data, using map is totally pointless and your component should return this:
return (
<div key={data.id}>
<h2>{data.title}</h2>
<h2>{data.userId}</h2>
<br />
</div>
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论