javascript - 无法从对象数组中获取数据 | React.js - openweatherAPI
问题描述
我使用 react-redux Toolkit 从 openweatherAPI 获取数据。我可以得到名字,但是当我想得到 main.temp 时,它给出了一个错误
typeError:无法读取未定义的属性(读取“临时”)
export const fetchDefault = createAsyncThunk('weather/getWeather', async (selectedCity) => {
const res = await axios(`https://api.openweathermap.org/data/2.5/weather?q=${selectedCity}&appid=6d735f036884219e3a12eeb6f7bf6f93`)
return res.data});
额外减速器
[fetchDefault.fulfilled]: (state , action) => {
state.item = action.payload;
console.log(state.item)
},
如果我return res.data.main
但这次不能得到名字,它会起作用。
index.js
const getCity = useSelector((state) => state.weather.item);
{getCity.main.temp} // Gives Error..
数组看起来像这样..
{
"weather": [
{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
}
],
"main": {
"temp": 300.15,
"pressure": 1007,
"humidity": 74,
"temp_min": 300.15,
"temp_max": 300.15
},
"wind": {
"speed": 3.6,
"deg": 160
"id": 2172797,
"name": "Cairns",
"cod": 200
}
解决方案
您的 reducer 保存action.payload
到state.item
,所以我认为useSelector
应该返回state.item.name
for getCity
(假设您想使用该选择器访问城市名称)。
或者,您可以创建一个选择器state.item
,并通过它访问所有内容。
顺便说一句,你的 reducer 应该返回一个值,所以假设 state 最初是一个对象,它应该看起来像:
[fetchDefault.fulfilled]: (state , action) => {
return {...state, item: action.payload}
},
推荐阅读
- python - 我在循环浏览文件夹并写入另一个文件夹时遇到问题
- javascript - 光滑的滑块响应断点在 576px 处不起作用
- cypress - 赛普拉斯中的并行请求
- javascript - 触发 Vue 函数更改某些组件字段时出现问题
- java - 如何读取以空格分隔的数字?
- android - 当我更改我的活动时,我的回收站视图不显示
- python - 布尔索引后如何删除列中的某些值?
- python - paho mqtt 客户端何时丢弃缓冲消息?
- typescript - 打字稿:定义类型,如 keyof,但具有特定的值类型
- javascript - 如何选择用户可以使用 JavaScript 切换到的所有 html 元素?