我真的遇到了一個問題——如果你運行下面的代碼,你會得到一個錯誤“型別錯誤:無法讀取未定義的屬性(讀取‘地圖’)”。
當我控制臺注銷“專案”變數時,我得到 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;
uj5u.com熱心網友回復:
我可以看到兩個錯誤
- 一個是您獲取的資料是一個物件,而您最初將其設定為陣列,并且您還使用了只能用于陣列的 map 函式。
- 最初你的陣列不包含
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>
);
uj5u.com熱心網友回復:
專案是一個陣列而不是物件,例如 [{...}, {...}] ,desiredseries 在物件內部,而不是專案。
<ul>
{items.map(item => item.dataseries.map(ds=> (
{console.log(ds)}
)))}
</ul>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318248.html
標籤:javascript 反应
