为什么`data.map()`函数在与从API获取的数据一起使用时不如预期工作?

huangapple go评论101阅读模式
英文:

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=>{...}

  1. import {useState} from 'react';
  2. const App = () => {
  3. const [data, setData] = useState({data: []});
  4. const [isLoading, setIsLoading] = useState(false);
  5. const [err, setErr] = useState('');
  6. const handleClick = async () => {
  7. setIsLoading(true);
  8. try {
  9. const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
  10. method: 'GET',
  11. headers: {
  12. Accept: 'application/json',
  13. },
  14. });
  15. if (!response.ok) {
  16. throw new Error(`Error! status: ${response.status}`);
  17. }
  18. const result = await response.json();
  19. console.log('result is: ', JSON.stringify(result, null, 4));
  20. setData(result);
  21. } catch (err) {
  22. setErr(err.message);
  23. } finally {]
  24. setIsLoading(false);
  25. }
  26. };
  27. console.log(data);
  28. return (
  29. <div>
  30. {err && <h2>{err}</h2>}
  31. <button onClick={handleClick}>Fetch data</button>
  32. {isLoading && <h2>Loading...</h2>}
  33. {data && data.map((person) => {
  34. return (
  35. <div key={person.id}>
  36. <h2>{person.title}</h2>
  37. <h2>{person.userId}</h2>
  38. <br />
  39. </div>
  40. );
  41. })}
  42. </div>
  43. );
  44. };
  45. 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,它将按预期工作 为什么`data.map()`函数在与从API获取的数据一起使用时不如预期工作?
如果您需要显示帖子数据,使用 map 是完全没有意义的,您的组件应该返回这个:

  1. return (
  2. <div key={data.id}>
  3. <h2>{data.title}</h2>
  4. <h2>{data.userId}</h2>
  5. <br />
  6. </div>
  7. );
英文:

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 为什么`data.map()`函数在与从API获取的数据一起使用时不如预期工作?
If what you need is to display post data, using map is totally pointless and your component should return this:

  1. return (
  2. &lt;div key={data.id}&gt;
  3. &lt;h2&gt;{data.title}&lt;/h2&gt;
  4. &lt;h2&gt;{data.userId}&lt;/h2&gt;
  5. &lt;br /&gt;
  6. &lt;/div&gt;
  7. );

huangapple
  • 本文由 发表于 2023年6月1日 23:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定