簡體   English   中英

類型錯誤:從 API 調用時無法讀取未定義的屬性(讀取“地圖”)

[英]TypeError: Cannot read properties of undefined (reading 'map') when calling from an API

我真的遇到了一個問題——如果你運行下面的代碼,你會得到一個錯誤“類型錯誤:無法讀取未定義的屬性(讀取‘地圖’)”。

當我控制台注銷“項目”變量時,我得到 2 個結果,如下所示: 在此處輸入圖片說明

問題在於第一個結果,因為它是空的。 但是有人可以向我解釋為什么這個結果是空的,為什么它會產生 2 個結果?

此代碼直接取自此處並進行了修改以適應從 API 返回的內容。 請考慮運行此代碼,以便您了解我的意思。

import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch("http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json")
  .then(res => res.json())
  .then(
    (result) => {
      setIsLoaded(true);
       setItems(result); 
    },
    // Note: it's important to handle errors here
    // instead of a catch() block so that we don't swallow
    // exceptions from actual bugs in components.
    (error) => {
      setIsLoaded(true);
      setError(error);
    }
  )
  }, [])


  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
return (
  <ul>
    {items.dataseries.map(item => (
       {console.log(item)}
    ))}
</ul>
    );
  }
}

export default App;

我可以看到兩個錯誤

  1. 一個是您獲取的數據是一個對象,而您最初將其設置為數組,並且您還使用了只能用於數組的 map 函數。
  2. 最初,您的數組不包含數據dataseries您也無法訪問數組中那樣的屬性(因為數組具有索引,我們可以通過該索引獲取那里的值)。

所以你可以做的是把這個函數設置成這樣

useEffect(() => {
fetch("http://www.7timer.info/bin/api.pllon=113.17&lat=23.09&product=astro&output=json")
.then(res => res.json())
.then(
  (result) => {
  setIsLoaded(true);
   setItems(result.dataseries); 
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
  (error) => {
    setIsLoaded(true);
    setError(error);
  }
)}, [])

並返回函數是這樣的

return (
  <ul>
    {items.map(item => (
      {console.log(item)}
    ))}
  </ul>
);

項目是一個數組而不是對象,例如 [{...}, {...}] ,desiredseries 在對象內部,而不是項目。

 <ul>
        {items.map(item => item.dataseries.map(ds=> (
           {console.log(ds)}
        )))}
    </ul>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM