尝试显示 API 输出数据时出现'Undefined const'错误



我正在尝试显示 CONST 国家代码以及 API 输出数据,但 REACT 说 const 未定义?
问题:1:有没有另一种方法可以显示常量? 问题 2:我如何将此 const 作为用户输入并在 API 中使用它以及与页面上的其他信息一起显示?

import React, { useEffect, useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
maxWidth: 1000,
margin: "0 auto",
marginTop: 50,
},
paper: {
padding: theme.spacing(2),
textAlign: "center",
color: theme.palette.text.secondary,
},
title: {
color: "#3f51b5",
textTransform: "uppercase", //could be slowing down?
},
}));
export default function CountryPanel() {
const classes = useStyles();
const countryCode = "ca";
const url =
"https://api.thevirustracker.com/free-api?countryTotal=" + countryCode;

const [globalData, setGlobalData] = useState({});

useEffect(() => {
getData(url);
async function getData(url) {
const response = await fetch(url);
let data = await response.json(); // convert to json
const countrycode = data.countrydata[0].info.code;
const countryname = data.countrydata[0].info.title;
const srcurl = data.countrydata[0].info.source;
console.log(countrycode, countryname, srcurl, "constants");
delete data.countrydata[0].info;

setGlobalData(data.countrydata[0]);
}, []);
return (
<div className={classes.root}>
<h1> Country Code: {countrydata[0].info.code}</h1> // ERROR not defined ??       
????
<Grid container spacing={3}>
{Object.keys(globalData).map((key, ind) => {
return (
<Grid item xs={12} sm={4} key={ind}>
..
</Grid>
</div>
);
}

第一次渲染组件时,可能会发生这种情况,当时countrydata不包含任何数据,并且您正在尝试访问 .
countrydata[0].info.code因此,如果countrydata本身不包含任何数据,则无法访问其属性。 为避免这种情况,您应该添加如下条件-

<h1> Country Code: {countrydata[0] && countrydata[0].info && countrydata[0].info.code}</h1>

它应该避免访问未定义属性的错误。因为logical AND可以防止这种情况.
查看更多 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

应该是:

<h1> Country Code: {globalData.info.code}</h1>

最新更新