javascript - TypeError:无法读取反应中未定义的属性'0'
问题描述
我正在开发天气应用程序。是学习项目。我收到错误。
我使用了 3 个组件。
应用程序.js:
<WeatherApiAddressProvider>
<WeatherCity />
</WeatherApiAddressProvider>
WeatherApiAddressProvider(上下文 API):
const setApiAddress = (city) => {
const address = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=7b7503a2aa9ca872738c7213619a72f5`;
return address;
};
export const WeatherApiAddressProvider = ({ children }) => {
return (
<WeatherContext.Provider value={setApiAddress}>
{children}
</WeatherContext.Provider>
);
};
WeatherCity.js:
const setApiAddress = useContext(WeatherApiAddressContext);
const [city, setCity] = useState("");
const handleChange = (e) => {
setCity(e.target.value);
};
return (
<div>
<div className="container">
<div className="row">
<div className="col">
<select
className="form-select mb-3"
aria-label="Default select example"
value={city}
onChange={handleChange}
>
<option className="placeholder" value="">
Please select a city
</option>
<option value="adana">Adana</option>
...
</select>
</div>
<div className="col">
<div className="p-5">
<WeatherDetail setApiAddress={setApiAddress} city={city} />
</div>
</div>
</div>
</div>
</div>
);
WeatherDetail.js:
const [weatherInfo, setWeatherInfo] = useState({});
let imgCode = weatherInfo.weather[0].icon;
useEffect(() => {
axios.get(city ? setApiAddress(city) : "").then((response) => {
setWeatherInfo(response.data);
});
}, [city, setApiAddress]);
return (
<div>
{city !== "" && (
<div className="card">
<img
className="card-img-top"
src={`https://openweathermap.org/img/wn/${imgCode}.png`}
/>
<div className="card-body">
<h5 className="card-title">{weatherInfo.name}</h5>
<p className="card-text">
Some quick example text to build on the card title and make up the
bulk of the card's content.
</p>
</div>
</div>
)}
{}
</div>
);
如您所知,WeatherApiAddressProvider
抛出setApiAddres
函数,WeatherCity
抛出城市变量。WeatherDetail
使用 .接收这些并从 weatherapi 获取数据axios
。
我得到的错误:
TypeError:无法读取未定义的属性“0”(让 imgCode = weatherInfo.weather[0].icon)
我尝试过的解决方案:
- 我记录了收到的数据(
weatherInfo
或response.data
),我看到这个数据是对象。然后我定义initialState(weatherInfo)
为对象,但它没有解决问题。 - 我创建了一个对象,例如在
initialState
. 但这并没有解决问题。
我想在 WeatherDetail.js 中显示天气代表图像和天气详细信息。我怎样才能做到这一点?
解决方案
更改表达式如下WeatherDetails.js
let imgCode = weatherInfo && weatherInfo.weather.length >0 && weatherInfo.weather[0].icon
推荐阅读
- java - 如何停止 JMH 基准测试?
- php - 动态任务调度器 - Laravel
- wpf - 在 XAML 中的 DrawingBrush 中旋转渐变
- python - 在 scikit-learn 版本 0.21.2 的 OneHotEncoder 中使用 active_features_ 和 feature_indices_
- wordpress - 更改运输方式后 Woocommerce 结帐页面重新加载
- c++ - Qt 错误消息“qt.network.ssl: QSslSocket::connectToHostEncrypted: TLS 初始化失败”
- android - 如何为相机添加白平衡
- expression - md5函数可以通过参数传递动态列列表吗
- vue.js - 从输入中提取动态数据到字符串中
- java - 使用 JNA 在“Internet Explorer_server”中操作 HTML 元素