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

React Redux报错:Cannot read property 'categoryName' of undefined 求助

解决React-Redux中"Cannot read property 'categoryName' of undefined"错误

我帮你排查了代码里的问题,发现几个关键错误导致了这个TypeError,咱们一步步来修复:

1. Reducer名称拼写错误(最直接原因)

在mapStateToProps函数里,你写了state.changeCategoryReducers,但根reducer中定义的reducer名称是changeCategoryReducer(多了末尾的s)。这就导致currentCategory拿到的是undefined,自然无法读取categoryName属性。

修改后的mapStateToProps:

function mapStateToProps(state) {
  return {
    currentCategory: state.changeCategoryReducer, // 去掉多余的s
    categories: state.categoryListReducer
  }
}

2. 拼写错误(附带修复)

在render方法里,你写了this.props.categories.legnth,这里的legnth是拼写错误,正确拼写是length,否则会导致分类数量显示异常:

<h3>Categories {this.props.categories.length}</h3> // 修正拼写

额外检查点(如果问题仍存在)

  • 确认你的categoryListReducer初始状态设置正确,应该返回initialState.categories,确保this.props.categories不会是undefined:
    // categoryListReducer.js示例
    import initialState from "./initialState";
    import * as actionTypes from "../actions/actionTypes";
    
    export default function categoryListReducer(state = initialState.categories, action) {
      switch(action.type) {
        case actionTypes.GET_CATEGORIES_SUCCESS:
          return action.payload;
        default:
          return state;
      }
    }
    
  • 确认Store配置时正确应用了Thunk中间件,确保异步action(getCategories)能正常执行:
    // store配置示例
    import { createStore, applyMiddleware } from "redux";
    import thunk from "redux-thunk";
    import rootReducer from "./reducers";
    
    const store = createStore(rootReducer, applyMiddleware(thunk));
    export default store;
    

按照以上步骤修改后,应该就能解决这个TypeError问题了。

内容的提问来源于stack exchange,提问作者Cihan Icelliler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:23:08