我目前正在开发一个项目,需要从对象或数组中提取图标。然而,我在这样做时遇到了困难。我的方法是将图标存储在变量中,然后将其作为道具传递给另一个组件。不幸的是,尽管采用了这种方法,但该功能并没有像我预期的那样工作。
这是我在控制台中遇到的错误:“无法读取未定义的属性(读取'0')”当我实现此代码时发生这种情况
<img src={props.icon} alt="cloud" />
,但效果很好
这是代码:
import React, { useEffect, useState } from "react";
import Weather from "./components/Weather";
import "./App.css";
function App() {
const [search, setSearch] = useState("");
const [data, setData] = useState([]);
useEffect(() => {
fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${search}&appid=1769e69d20183ccd0c32ac3215db1d40&units=metric`
)
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error));
}, [search]);
const handleInput = (event) => {
setSearch(event.target.value);
};
let icon = data.weather[0].icon + ".png";
return (
<div>
<Weather icon={icon} inputValue={handleInput} showItems={data} />
</div>
);
}
export default App;
import "./style/Weather.css";
import "@fortawesome/fontawesome-free/css/all.css";
function Weather(props) {
// const data = [
// {
// coord: {
// lon: -0.1257,
// lat: 51.5085,
// },
// weather: [
// {
// id: 804,
// main: "Clouds",
// description: "overcast clouds",
// icon: "04d",
// },
// ],
// base: "stations",
// main: {
// temp: 285.69,
// feels_like: 285.19,
// temp_min: 284.29,
// temp_max: 286.64,
// pressure: 1015,
// humidity: 84,
// },
// visibility: 10000,
// wind: {
// speed: 5.14,
// deg: 210,
// },
// clouds: {
// all: 100,
// },
// dt: 1710850556,
// sys: {
// type: 2,
// id: 2075535,
// country: "GB",
// sunrise: 1710828286,
// sunset: 1710871895,
// },
// timezone: 0,
// id: 2643743,
// name: "London",
// cod: 200,
// },
// ];
return (
<div className="container">
<div className="weather-container">
<input
onChange={props.inputValue}
type="text"
placeholder="Enter a city name"
/>
<p>{props.showItems.name}</p>
<img src={props.icon} alt="cloud" />
{props.showItems.main && <p>{props.showItems.main.temp.toFixed()}°C</p>}
</div>
</div>
);
}
export default Weather;
无法读取未定义的属性(读取“0”)
大概这发生在这里:
let icon = data.weather[0].icon + ".png";
什么是
data
?这是一个空数组:
const [data, setData] = useState([]);
数组,无论是空数组还是其他数组,都没有称为
weather
的属性。您的意思是读取数组的第一个element吗?例如:
let icon = data[0].weather[0].icon + ".png";
即使这样你也需要可选链,因为数组最初是空的:
let icon = data[0]?.weather[0].icon + ".png";
您可以在任何时候访问可能不存在的属性/索引时包含可选链。当然请记住,
icon
将会是意想不到的东西,例如 "null.png"
。
您还可以将其设置为某些默认值并有条件地覆盖它。例如:
let icon = "default.png";
if (data.length > 0) {
icon = data[0].weather[0].icon + ".png";
}
当然,这一切完全取决于
data
实际包含的内容。您将其初始化为数组,但我们在这里讨论的代码行假设它是一个对象。是哪一个?
您需要了解数据的结构才能使用该数据。但无论您如何看待它,如何使用它都需要支持初始(空)状态和填充数据的后续状态。