javascript - 报错 .map() is not a function

标签 javascript arrays reactjs

我卡在这个错误“.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/

相关文章:

javascript - Nvd3 : How prevent to display chart between -1 and 1 if have all y values 0?

javascript - 过滤数组以产品 checkin 事件记录

java - 将 2 个数组链接或合并为 1 个数组并在 java 中对它们进行排序

reactjs - 在React中,尝试根据传递给url的ID显示不同的图像

javascript - 为什么我不能在 React Native 组件中使用 connect ?

javascript - Cordova - 防止后退按钮关闭 Android 上的应用程序

javascript - 如何将 Terser 与 webpack 结合使用

javascript - 在没有 .concat 的情况下基于索引合并 JavaScript 数组

javascript - 多列数组中最接近的最大值

reactjs - 使用 useState 通过单击按钮来响应更新状态