我不是一个非常有经验的开发人员,所以我可能会遗漏一些简单的东西。我有一组从我的 redux 状态 (this.props.assignments.assignments) 获得的对象。当我尝试在我的渲染返回中调用 displayAssignments() 时,我得到一个 .map() is not a function。但是,我有另一个附加到 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.assignments
是一个 Array
。
关于javascript - .map() 在 render 函数之外工作,但在 render 内部使用时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56077978/