出现错误:.map() 不是函数。

3
我卡在这个错误上了:".map is not a function"

类型错误
teachers.map 不是一个函数


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>
    );
  }
}

代码片段 链接

3个回答

1

“.map不是一个函数”

这是一个非常常见的错误信息,它意味着您正在循环遍历的对象不是数组。

在您的代码中所做的是,当您点击按钮并触发handleView时,您将状态中的教师列表从有效的数组更改为布尔类型的某些内容:

let teachers = this.state.teachers;
this.setState({
  teachers: !teachers // here
});

在更改状态后,React会快速渲染新状态,但随后发现自己循环遍历布尔值而不是数组,从而触发您所看到的错误。

更新

正如其中一位回答所猜测的那样,我认为您正在尝试更改showPersons而不是teachers数组。


0

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,
  });
};

Edit withered-water-ji3lb


0
使用此代码,您可以将布尔值分配给先前的数组值。您不能在布尔值上使用map函数。
this.setState({
  teachers: !teachers
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接