我想制作一個以天氣為主題的網路。我在構建程序中達到了圖示應該隨著天氣變化而變化的觀點。
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:無法讀取未定義的屬性(讀取'0')shiftIcon E:/Projects and trainings/Education Courses/react.js courses/Person/weather-application/src/components/boxNew.js:32 29 | 讓 shiftIcon = () => { 30 | 31 | 讓圖示 = ""
32 | 讓 iconText = data.date[0].weather.code; | ^ 33 | 34 | 如果 (iconText == 600) { 35 | 圖示=“https://img.icons8.com/external-those-icons-lineal-color-those-icons/48/000000/external-wind-weather-those-icons-lineal-color-those-icons.png ";
uj5u.com熱心網友回復:
最初data是未定義的。您應該使用可選鏈接來擺脫運行時例外。
像這樣試試
let iconText = data?.date?.[0]?.weather?.code;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419176.html
標籤:
