无法读取未定义的属性(读取 'response')

Cannot read properties of undefined (reading 'response')

从 API 获取数据时出错,我需要的实际数据是响应。 但是当我尝试访问它时,它只是显示为未定义。我添加了一个加载功能但是 似乎没有解决它。

Ex Json(原文太大)

{
    "request": {
     
    },
    "response": [
      {
      Data I want here
       }

choose.js

const [data, setData] = useState();
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    setLoading(true);
    fetch(
  //example API key 
      "https://airlabs.co/api/v9/flights?api_key=2a6ae284-575d-41d8-948a-b789734174dd&arr_icao=VOBL"
    )

      .then((res) => res.json())
      .then((data) => {
        setData(data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

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

{data.response.map((post) => {

})

完整代码 link - https://codesandbox.io/s/heuristic-wood-meecre?file=/choose.js:2042-2072

您需要从 true 的加载状态开始,因为在初始渲染时您还没有 data

同时将您在 map 中所做的渲染移动到它自己的组件中,否则您会收到有关太多挂钩的运行时错误:

{data.response.map((post) => (
        <Inner post={post} />
      ))}

(这里渲染每个航班数据的组件简单命名为“Inner”)

你可以看到这个 sandbox 完整的演示。