首页 > 解决方案 > 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
}

标签: javascriptreactjs

解决方案


您需要初始化useState变量。试试这个:

const [latest, setLatest] = useState({ cases: "" });

解释
在点击 api 之前,当 react 尝试渲染您的组件时,{latest.cases}由于 insn 未初始化而引发错误latest,因此采用undefined.


推荐阅读