如何解决以下 TypeError: 无法读取未定义的属性
这是我一直在使用的 api 的链接。 API 链接在这里
import React, { useEffect, useState } from "react";
const Statewise = () => {
const [data, setData] = useState([]);
const getCovidData = async () => {
const res = await fetch('https://data.covid19india.org/data.json');
const actualData = await res.json();
console.log(actualData.statewise);
setData(actualData.status);
}
useEffect(() => {
getCovidData();
}, []);
return (
<>
<div className="container-fluid mt-5">
<div className="main-heading">
<h1 className="mb-5 text-center">COVID-19 Dashboard</h1>
</div>
<div className="table-responsive">
<table className="table table-hover">
<thead className="thead-dark">
<tr>
<th>State</th>
<th>Confirmed</th>
<th>Recovered</th>
<th>Deaths</th>
<th>Latest</th>
<th>Active</th>
</tr>
</thead>
<tbody>
{
data.map((currElem, ind) => {
return (
<tr key={ind}>
<th>{currElem.state}</th>
<td>{currElem.confirmed}</td>
<td>{currElem.recovered}</td>
<td>{currElem.deaths}</td>
<td>{currElem.lastupdatedtime}</td>
<td>{currElem.active}</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
</>
)
}
export default Statewise;
控制台上显示的错误如下所示。请提供解决方法。由于此错误,页面未呈现,无法显示任何数据。
Uncaught TypeError: Cannot read properties of undefined (reading 'map') at Statewise (statewise.js:37:1) at renderWithHooks (react-dom.development.js:16305:1) at updateFunctionComponent (react-dom.development.js:19588:1) at beginWork (react-dom.development.js:21601:1) at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1) at invokeGuardedCallback (react-dom.development.js:4277:1) at beginWork$1 (react-dom.development.js:27451:1) at performUnitOfWork (react-dom.development.js:26557:1) at workLoopSync (react-dom.development.js:26466:1)
我尝试重写 API 的名称,但没有成功。我没有得到解决方案。我尝试再次执行映射过程,但它显示相同的错误。
无法读取未定义的属性(读取“map”)
我知道您是新手,但请务必学习这一点,因为您正在习惯语言的错误。错误表明您无法读取未定义的属性,这意味着他们正在尝试访问对象的属性,而该对象未定义。此外,
读取“map”
可帮助您了解它正在读取哪个对象。最后一条消息应表明它正在从未定义的对象中读取
map
属性,如果您在代码中搜索
data.map
并且数据似乎未定义;如果它可能为空或未定义,甚至不是数组,请确保在调用map函数之前对其进行验证。
一个简单的
data && data.map(...)
就可以做到这一点,因为它会在调用map之前验证数据是否已定义。