首页 > 解决方案 > React-redux 映射错误 TypeError:无法读取未定义的属性“映射”

问题描述

我的 ReactJS 代码中出现以下错误:

TypeError:无法读取未定义的属性“地图”

这基于以下代码:

import React, { Component } from "react";
import { connect } from "react-redux";
import { ListGroup, ListGroupItem } from "reactstrap";
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</h3>
        <ListGroup>
          {this.props.categories.map(category => (
            <ListGroupItem key={category.id}>
              {category.categoryName}
            </ListGroupItem>
          ))}
        </ListGroup>
        <h5>The Category: {this.props.currentCategory.categoryName}</h5>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    currentCategory: state.changeCategoryReducer,
    categories: state.CategoryListReducer,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      getCategories: bindActionCreators(
        categoryActions.getCategories,
        dispatch
      ),
      changeCategory: bindActionCreators(
        categoryActions.getCategories,
        dispatch
      ),
    },
  };
}
export default connect(mapStateToProps)(CategoryList);

我不知道如何解决这个错误。你能帮我吗?

标签: javascriptjsonreactjsreduxreact-redux

解决方案


在使用 map() 之前,使用条件来检查钩子是否具有一定的价值。如果不是,条件将不起作用,不会显示任何内容,您也不会收到任何错误。


推荐阅读