我不是一个非常有经验的开发人员,所以我可能缺少一些简单的东西。我有一系列从redux状态(this.props.assignments.assignments)中获取的对象。尝试在渲染返回中调用displayAssignments()时,我得到的.map()不是函数。但是,我还有一个附加到onClick的函数,该函数执行相同的映射并将“名称”记录到控制台中,并且该函数按预期工作(当我注释掉displayAssignments()时)。我不知道为什么.map()可以在我的onClick而不是displayAssignments上工作。

我加入了showAssignments函数只是为了测试我的数据是否可以被映射...这使我更加困惑,因为它可以工作...

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getAssignments } from '../../Actions/assignmentActions.js';

class Assignments extends Component {
  componentDidMount() {
    this.props.getAssignments();
  };

  showAssignments = () => {
    console.log(this.props.assignments.assignments);
    this.props.assignments.assignments.map(assignment => (
      console.log(assignment.name)
    ));
  };
  displayAssignments = () => {
    this.props.assignments.assignments.map(assignment => {
      return (
        <div>
          <p>{assignment.name}</p>
          <p>{assignment.description}</p>
        </div>
      )
    })
  };

  render() {
    return (
      <div>
        <h1>Assignments</h1>
        <button onClick={this.showAssignments}>Click Me</button>
        {this.displayAssignments()}
      </div>
    );
  };
};

Assignments.propTypes = {
  getAssignments: PropTypes.func.isRequired,
  assignments: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  assignments: state.assignments
});

export default connect(mapStateToProps, { getAssignments })(Assignments);


预期:通过映射呈现作业的名称和描述
实际:获取this.props.assignments.assignments.map不是函数

最佳答案

您应该以map()的值返回displayAssigments

displayAssignments = () => {
    return this.props.assignments.assignments.map(assignment => {
      return (
        <div>
          <p>{assignment.name}</p>
          <p>{assignment.description}</p>
        </div>
      )
    })
  };


或只取下包裹.map()的花括号:

displayAssignments = () => this.props.assignments.assignments.map(assignment =>
  <div>
    <p>{assignment.name}</p>
    <p>{assignment.description}</p>
  </div>
)


由于您的错误不起作用,请确保this.props.assignments.assignmentsArray

07-24 17:38