You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Redux Toolkit渲染默认城市天气报reading 'name' of undefined错误

问题根因

  • 你的weatherSlice初始状态里item设为空数组[],但接口返回的天气数据是对象结构,类型不匹配
  • 接口请求是异步的,首次渲染时请求还未完成,getCity还是初始的空数组,不存在location属性,读取location.name自然触发类型错误
  • Slice配置存在拼写错误:字段是extraReducers不是nextraReducers,会导致请求成功后数据无法正确更新到state中

修复步骤

步骤1:修正WeatherSlice配置&调整初始状态

export const weatherSlice = createSlice({   
  name: "weather",
  initialState : {
    item: null, // 改为null更方便判断加载状态
    loading: false // 新增loading状态方便做加载提示
  },
  reducers:{},
  extraReducers:{ // 修正拼写错误
    [fetchDefault.pending]: (state) => {
      state.loading = true
    },
    [fetchDefault.fulfilled]: (state , action) => {
      state.loading = false
      state.item = action.payload;
    },
    [fetchDefault.rejected]: (state) => {
      state.loading = false // 补充失败状态,避免一直处于加载中
    }
  }
})

步骤2:组件渲染增加安全判断

二选一即可:

方案1:可选链操作符(代码改动最小)

直接在读取属性处加可选链,属性不存在时返回undefined不会触发报错:

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

方案2:条件渲染+加载提示(用户体验更好)

// 取数时同步拿到loading状态
const {item: getCity, loading}  = useSelector((state) => state.weather);
useEffect(() => {
  dispatch(fetchDefault(selectedCity))
}, [dispatch, selectedCity]) // 把selectedCity加入依赖数组,切换城市时会自动重新请求

// 加载中先显示提示
if(loading) return <div>天气数据加载中...</div>

// 加载完成后再渲染数据
return (
  <Typography className="label" variant="h5" sx={{pb:5}} component="div">
    {getCity.location.name}
  </Typography>
)

额外注意事项

你的App.js中Route写法存在冗余,react-router v5中如果指定了component属性就不需要再写对应子组件,否则会重复渲染,修正为:

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

内容的提问来源于stack exchange,提问作者Fatih Can

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:06:04