Hi是一个新手反应,但我困在这个错误“。地图不是一个功能”需要帮助
TypeError
teachers.map is not a function
class toggleView extends React.Component {
constructor(props) {
super(props);
this.state = {
teachers: ["Willis", "Duke", "Davis", "Walter"],
showPersons: false
};
this.handleView = this.handleView.bind(this);
}
handleView = e => {
e.preventDefault();
let teachers = this.state.teachers;
this.setState({
teachers: !teachers
});
};
render() {
let teachers = this.state.teachers;
let individualTeacher = teachers.map(teacher => <li> {teacher} </li>);
let person = null;
if (this.state.showPersons === true) {
person = <li>{individualTeacher}</li>;
} else {
person = null;
}
return (
<div>
<h3> Heloo folks </h3>
<button onClick={this.handleView}>Toggle View</button>
<br />
<br />
<ul>{person}</ul>
</div>
);
}
}
代码段链接
。map不是函数
是非常常见的错误消息,它意味着您正在循环通过的对象不是数组。
您在代码中所做的是,当您单击按钮并触发handleView时,您将教师列表的状态从有效数组更改为布尔类型:
let teachers = this.state.teachers;
this.setState({
teachers: !teachers // here
});
在改变状态后,React会快速呈现新的状态,但随后发现自己循环通过一个布尔值而不是数组,从而触发您看到的错误。
更新
正如其中一个答案所猜测的那样,我认为你正在试图改变作秀者而不是教师阵型。
Teachers
是一个数组,在HandleView
上,您分配了一个布尔值而不是数组,因此在下一个呈现中,您尝试#array.map()
一个布尔值,这导致了运行时错误。
// teachers is an array
let teachers = this.state.teachers;
// teachers will be a boolean after the render
// ![] === false
this.setState({
teachers: !teachers,
});
我认为您的意思是使用showpersons
代替。
handleView = (e) => {
e.preventDefault();
let showPersons = this.state.showPersons;
this.setState({
showPersons: !showPersons,
});
};
使用此代码,您将一个布尔值赋给上一个数组值。 不能将map函数与布尔值一起使用
this.setState({
teachers: !teachers
});