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

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

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

return (
&lt;div key={data.id}&gt;
&lt;h2&gt;{data.title}&lt;/h2&gt;
&lt;h2&gt;{data.userId}&lt;/h2&gt;
&lt;br /&gt;
&lt;/div&gt;
);

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:

确定