【发布时间】:2020-07-06 04:10:29
【问题描述】:
我在 return 之前定义了一个 const( 但是当我尝试渲染它时,得到它未定义的错误。
我正在为 REACT 的概念而苦苦挣扎。 RETURN 之前定义的任何常量或变量都不能在 ?? 中渲染?
是不是只有 setState 变量可以渲染?
这是代码。我从 API 数据中保存了 var countryname,但是当我尝试渲染它时,显示为 UNDEFINED
./src/components/CountryPanel.jsx 第 83:49 行:'countryname' 未定义 no-undef
export default function CountryPanel(props) {
const classes = useStyles();
let countryCode = props.countryCode
let url =
"https://api.thevirustracker.com/free-api?countryTotal=" + countryCode;
const [globalData, setGlobalData] = useState({});
const [countryName, setCountryName] = useState("");
useEffect(() => {
getData(url);
async function getData(url) {
const response = await fetch(url);
let data = await response.json(); // convert to json
const countryname = data.countrydata[0].info.title;
delete data.countrydata[0].info;
setCountryName(countryname);
setGlobalData(data.countrydata[0]);
}
}, []);
return (
<div className={classes.root}>
<h3>
Stats for: {countryCode} {countryName} {countryname}
</h3>
最后三个是未定义的,虽然我是从 API 数据中保存的 const countryname = data.countrydata[0].info.title; (..name - n 小写)
【问题讨论】:
-
你能添加你的代码吗?
-
我的问题是:为什么反应说“国家名称未定义”。我在“返回”之前从 API 数据中保存了它。返回 (
统计信息:{countryCode} {countryName} {countryname}
我没有得到我的问题的答案:为什么我不能渲染/显示 {countryname} ???为什么我必须将它保存到状态来渲染它?有没有办法在不保存到状态的情况下渲染它?返回 (统计信息:{countryCode} {countryName} {countryname}