通过更改 API 数据来更改图标
Change the icon by changing the API data
我想制作一个以天气为主题的网站。我在构建过程中讲到图标应该随着天气的变化而变化。
let shiftIcon = () => {
let icon = "";
let iconText = data.date[0].weather.code;
if (iconText == 600) {
icon = "https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png";
return (
<img src={icon} />
);
} else {
return null;
}
}
<div className="col col-3">
{shiftIcon()}
</div>
写完这段代码后,我得到了一个错误。您对此有解决方案吗?
TypeError: Cannot read properties of undefined (reading '0') shiftIcon
E:/Projects and trainings/Education Courses/react.js
courses/Person/weather-application/src/components/boxNew.js:32 29 |
let shiftIcon = () => { 30 | 31 | let icon = ""
32 | let iconText = data.date[0].weather.code;
| ^ 33 | 34 | if (iconText == 600) { 35 | icon =
"https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png";
最初 data
未定义。您应该使用 optional chaining 来消除运行时异常。
这样试试
let iconText = data?.date?.[0]?.weather?.code;
我想制作一个以天气为主题的网站。我在构建过程中讲到图标应该随着天气的变化而变化。
let shiftIcon = () => {
let icon = "";
let iconText = data.date[0].weather.code;
if (iconText == 600) {
icon = "https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png";
return (
<img src={icon} />
);
} else {
return null;
}
}
<div className="col col-3">
{shiftIcon()}
</div>
写完这段代码后,我得到了一个错误。您对此有解决方案吗?
TypeError: Cannot read properties of undefined (reading '0') shiftIcon E:/Projects and trainings/Education Courses/react.js courses/Person/weather-application/src/components/boxNew.js:32 29 | let shiftIcon = () => { 30 | 31 | let icon = ""
32 | let iconText = data.date[0].weather.code; | ^ 33 | 34 | if (iconText == 600) { 35 | icon = "https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png";
最初 data
未定义。您应该使用 optional chaining 来消除运行时异常。
这样试试
let iconText = data?.date?.[0]?.weather?.code;