首页 > 解决方案 > TypeError: Cannot read properties of undefined (reading 'name') - React , redux-toolkit

问题描述

我使用 react-redux Toolkit 从 API 获取数据。想要在页面渲染时显示默认城市天气数据,但它给出了错误

TypeError:无法读取未定义的属性(读取“名称”)

输出 - > index.js 的空数组比 WeatherSlice.js 的 API 输出

export const fetchDefault = createAsyncThunk('weather/getWeather', async (selectedCity) => {
const res = await axios(`http://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=${selectedCity}&days=10&aqi=no&alerts=no
`)
return res.data 

});

<Typography className="label" variant="h5" sx={{pb:5}} component="div">
                 {getCity.location.name} // GivesTypeError
    </Typography>

主页组件

const getCity  = useSelector((state) => state.weather.item);
useEffect(() => {
    dispatch(fetchDefault(selectedCity))
    console.log()

}, [dispatch])

应用程序.js

<Switch>
    <Route path="/about" component={About} >
      <About />
    </Route>
    <Route path="/" component={Home}>
      <Home />
    </Route>
  </Switch>

Store.js

 export const store = configureStore({
  reducer: {
    weather : weatherSlice.reducer,
  },
})

WeatherSlice.js

export const weatherSlice = createSlice({   
name: "weather",
initialState : {
    item : [],
},
reducers:{},
extraReducers:{
    [fetchDefault.fulfilled]: (state , action) => {
       
        state.item = action.payload;
        console.log(state.item)
    },
    [fetchDefault.pending]: (state , action) => {
       
        console.log("sadsad")
    }
}

标签: javascriptreactjsreact-redux

解决方案


我检查了您使用的 api ( https://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=Istanbul&days=10&aqi=no&alerts=no ) 看看它返回了什么。

响应数据是具有以下字段的对象:位置、当前和预测。

所以起初,我认为“项目”的初始状态不应该是一个空数组,因为 api 不返回一个数组,而是它应该是未定义或空对象。

那么,TypeError 存在的主要原因是您无法检索数据或无法填写状态中的项目。您应该检查从 api 返回的数据。你能成功检索数据并用它填充状态吗?

TypeError 的原因:如果您有一个空数组或空对象并尝试通过此元素访问字段(如 item.location),则不会显示错误,但如果您尝试访问字段的字段(如 item.location)。 location.name) 发生 TypeError。

在组件之前检查对象也会更安全。像:

// can be undefined comparison or getCity.length > 0 etc
{getCity !== undefined && (
        <Typography className="label" variant="h5" sx={{pb:5}} component="div">
              {getCity.location.name} // GivesTypeError
        </Typography>
)}

推荐阅读