首页 > 解决方案 > 无法从对象数组中获取数据 | 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
 }

标签: javascriptreactjsreact-reduxopenweathermap

解决方案


您的 reducer 保存action.payloadstate.item,所以我认为useSelector应该返回state.item.namefor getCity(假设您想使用该选择器访问城市名称)。

或者,您可以创建一个选择器state.item,并通过它访问所有内容。

顺便说一句,你的 reducer 应该返回一个值,所以假设 state 最初是一个对象,它应该看起来像:

[fetchDefault.fulfilled]: (state , action) => {
    return {...state, item: action.payload}        
},

推荐阅读