我卡在这个错误“.map 不是一个函数”
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>
);
}
}
代码片段 link
最佳答案
.map is not a function
是很常见的错误信息,它意味着你正在循环的对象不是一个数组。
您在代码中所做的是,当您单击按钮并触发 handleView 时,您将状态中的教师列表从有效数组更改为 bool 类型:
let teachers = this.state.teachers;
this.setState({
teachers: !teachers // here
});
更改状态后,React 将快速呈现新状态,但随后发现自己循环遍历 bool 值而不是数组,从而触发您看到的错误。
更新
作为猜测的答案之一,我认为您正在尝试更改 showPersons 而不是 teachers 数组。
关于javascript - 报错 .map() is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62610836/