【发布时间】:2021-10-16 01:00:33
【问题描述】:
我真的遇到了一个问题——如果你运行下面的代码你会得到一个错误“TypeError: Cannot read properties of undefined (reading 'map') ”。
当我在控制台注销“items”变量时,我得到 2 个结果,如下所示:
问题在于第一个结果,因为它是空的。但是有人可以向我解释为什么这个结果是空的以及为什么它会产生 2 个结果吗?
此代码直接取自 here,并进行了修改以适应 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;
【问题讨论】:
-
您的
items状态变量在首次加载时没有dataseries属性。在使用map渲染之前,您需要在渲染函数中检查它。
标签: javascript reactjs