You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用fetch()获取API数据:无法访问数组,报item未定义错误

Fixing the "item is not defined" Error in Your React API Component

Hey there! It’s super frustrating when you can see the data coming through in DevTools but can’t get it to render—let’s break this down step by step to fix that item is not defined error.

First, Let’s Rule Out the Most Common Culprits

1. Your Initial State Isn’t Set Up for an Array

If you initialized your state as undefined or null instead of an empty array, React might try to render before the API call finishes, leading to errors when you try to map over it.

Bad Initial State:

const [apiData, setApiData] = useState(); // No initial value = undefined

Fixed Initial State:

const [apiData, setApiData] = useState([]); // Initialize with empty array

2. You’re Not Accessing the Correct Array in Your API Response

Chances are, your API response wraps the array you need in an object (like { items: [...] } instead of returning the array directly). If you’re trying to map over the top-level response object instead of the nested array, you’ll hit errors.

Let’s say your DevTools shows data like this:

{
  "status": "success",
  "data": [
    { "id": 1, "name": "First Item" },
    { "id": 2, "name": "Second Item" }
  ]
}

Bad Mapping (Trying to map the whole response):

return (
  <div>
    {apiData.map(item => <p key={item.id}>{item.name}</p>)} 
    // Error: apiData is the full object, not the array!
  </div>
);

Fixed Mapping (Target the nested array):

return (
  <div>
    {apiData.data?.map(item => <p key={item.id}>{item.name}</p>)}
    // Use ?. to safely access the array before it loads
  </div>
);

3. You Have a Typo in Your Map Callback Variable

Double-check that the variable name in your map callback matches what you’re using inside the JSX. A tiny typo like itm instead of item will throw that "not defined" error instantly.

Bad Typo Example:

apiData.data.map(itm => <p key={itm.id}>{item.name}</p>) 
// Oops! Used "itm" in the callback but "item" in JSX

Fixed Version:

apiData.data.map(item => <p key={item.id}>{item.name}</p>)
// Variable name matches throughout

4. You’re Not Handling Loading State

Even with an empty array initial state, it’s good practice to add a loading check to avoid any edge cases where the data hasn’t populated yet.

Add Loading State:

const [apiData, setApiData] = useState([]);
const [isLoading, setIsLoading] = useState(true);

useEffect(() => {
  fetch("/your-api-endpoint")
    .then(res => res.json())
    .then(data => {
      setApiData(data);
      setIsLoading(false);
    })
    .catch(err => console.error(err));
}, []);

if (isLoading) {
  return <div>Loading data...</div>;
}

return (
  <div>
    {apiData.data?.map(item => <p key={item.id}>{item.name}</p>)}
  </div>
);

Quick Recap to Debug Fast

  1. Confirm your state starts as an empty array
  2. Match your code’s array access to the exact structure from DevTools
  3. Scan for typos in your map variable names
  4. Add a loading state to handle the gap before API data arrives

That should get your items rendering properly in no time!

内容的提问来源于stack exchange,提问作者George Morris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:22:14