【问题标题】:React TypeError: Cannot read property 'categoryName' of undefined problemReact TypeError:无法读取未定义问题的属性'categoryName'
【发布时间】:2020-12-30 11:07:06
【问题描述】:

我正在尝试从 initialState 获取我的 categoryName,但它显示“TypeError:无法读取未定义问题的属性 'categoryName'”。我该如何解决这个案子? 这是我的 initialState.js 文件:

export default {
  currentCategory:{categoryName:"Beverages"},
  categories:[]
};

这是我的 categoryList.js 文件:

import React, { Component } from "react";
import { connect } from "react-redux";
import {bindActionCreators} from 'redux'
import * as categoryActions from '../../redux/actions/categoryActions'


class CategoryList extends Component {
  componentDidMount(){
    this.props.actions.getCategories()
  }
  render() {
    return (
      <div>
        <h3>Categories {this.props.categories.legnth}</h3>
        <h5>Seçili Kategori: {this.props.currentCategory.categoryName}</h5>
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    currentCategory: state.changeCategoryReducers,
    categories:state.categoryListReducer
  }
}
function mapDispatchToProps(dispatch){
  return {
    actions:{
      getCategories:bindActionCreators(categoryActions.getCategories,dispatch)
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(CategoryList);

我正在使用 reducers、redux 和 thunk,但我有一个问题,我认为应该是安装问题。但我无法解决错过了哪个包裹。对于任何建议都会非常有效。 这是我的 changeCategoryReducer.js:

import * as actionTypes from "../actions/actionTypes";
import initialState from "./initialState";

export default function changeCategoryReducer(
  state = initialState.currentCategory,
  action
) {
  switch (action.type) {
    case actionTypes.CHANGE_CATEGORY:
      return action.payload;

    default:
      return state;
  }
}

这是我的 index.js 文件:

import { combineReducers } from "redux";
import changeCategoryReducer from "./changeCategoryReducer";
import categoryListReducer from './categoryListReducer';


const rootReducer = combineReducers({
  changeCategoryReducer,
  categoryListReducer,
});

export default rootReducer;

【问题讨论】:

  • 如果您在componentDidMount 中获取类别,那么类别将在第一次渲染时未定义。
  • 我该如何解决这个问题?
  • 在第一次渲染时有条件地渲染组件,return() {&lt;div&gt;{categories.length &gt; 0 ? &lt;h3&gt;Categories {this.props.categories.categoryName}&lt;/h3&gt; : &lt;h3&gt;Loading...&lt;/h3&gt; }&lt;/div&gt;}
  • 可能在您的 mapStateToProps 中,您正在映射 state.changeCategoryReducer 而不是 state.changeCategoryReducer。有一个额外的(s)。错字
  • @Tauseef Ahmad 你是完美的!我不知道你怎么看。但我非常感谢你。你拯救了我的一天

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

我没有看到这条线:currentCategory: state.changeCategoryReducers, 但是@Tauseef Ahmad 看到了。 应该是这样的:currentCategory: state.changeCategoryReducer,

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 2020-12-05
    • 2022-01-01
    • 2020-05-09
    • 2020-07-24
    • 1970-01-01
    • 2023-04-01
    • 2021-09-04
    相关资源
    最近更新 更多