javascript - TypeError:无法读取未定义的属性“案例”
问题描述
我想在 react.js 中建立一个网站。我调用了一个 api,这个 api 中有一些属性。当我调用任何属性时,都会遇到错误消息。我想在我的网站上显示“cases”属性,但是当尝试访问“case”属性表单状态时,会出现此错误“TypeError:无法读取未定义的属性“cases””
我的代码
import Card from "react-bootstrap/Card";
import CardDeck from "react-bootstrap/CardDeck";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import axios from "axios";
function App() {
const [latest, setLatest] = useState();
useEffect(()=>{
axios
.get("https://corona.lmao.ninja/v2/all")
.then (res=>{
setLatest(res.data);
})
.catch(err=>{
console.log(err);
})
})
return (
<div>
<CardDeck>
<Card
bg="secondary"
text="white"
className="text-center"
style={{ margin: "10px"}}
>
<Card.Body>
<Card.Title>Cases</Card.Title>
<Card.Text>{latest.cases}</Card.Text>
</Card.Body>
<Card.Footer>
<small>Last updated 3 mins ago</small>
</Card.Footer>
</Card>
错误信息
×
TypeError: Cannot read property 'cases' of undefined
App
C:/webdevelopment/project/covid/src/App.js:34
31 | >
32 | <Card.Body>
33 | <Card.Title>Cases</Card.Title>
> 34 | <Card.Text>{latest.cases}</Card.Text>
| ^ 35 | </Card.Body>
36 | <Card.Footer>
37 | <small>Last updated 3 mins ago</small>
View compiled
api
{
"updated": 1599367649631,
"cases": 27065812,
"todayCases": 11648,
"deaths": 883742,
"todayDeaths": 566,
"recovered": 19166178,
"todayRecovered": 10236,
"active": 7015892,
"critical": 60720,
"casesPerOneMillion": 3472,
"deathsPerOneMillion": 113.4,
"tests": 536587691,
"testsPerOneMillion": 69041.61,
"population": 7771946760,
"oneCasePerPeople": 0,
"oneDeathPerPeople": 0,
"oneTestPerPeople": 0,
"activePerOneMillion": 902.72,
"recoveredPerOneMillion": 2466.07,
"criticalPerOneMillion": 7.81,
"affectedCountries": 215
}
解决方案
您需要初始化useState
变量。试试这个:
const [latest, setLatest] = useState({ cases: "" });
解释
在点击 api 之前,当 react 尝试渲染您的组件时,{latest.cases}
由于 insn 未初始化而引发错误latest
,因此采用undefined
.
推荐阅读
- c# - C# 根据另一个数组中的索引递增数组中的 Int
- python - 函数被调用的次数
- tensorflow.js - 绘制 x 和 y 张量
- mysql - 如何用某些东西替换占位符以使此 SQL 语句的第一个条件始终为 TRUE?
- asp.net-web-api - 使用 xUnit 和 .Net Core MVC 控制器为 CORS 创建单元测试
- android - 如何将 Flutter (Dart) 与我的 Oracle 服务器连接起来?有人试过吗?
- java - JAXB如何强制解组中的某个顺序
- python - Python:python如何在一条语句中执行多个布尔值?
- bash - Bash tr sed / awk 具有挑战性的脚本
- php - 我需要做什么才能查看数据库项目(foreach 循环)