`this.setState` 不是绑定函数中的函数

`this.setState` not a function in a bound function

抱歉,我看到这个问题已经被问过几次了。我以前解决过这个问题,但我知道我正在以一种新的方式看待它。

这是我在通量存储中的构造函数:

class TodoStore extends EventEmitter {
  constructor() {
    super()
    this.state = {
      todos: [
        {
          id: uuid(),
          text: 'Go Shopping',
          complete: false
        },
        {
          id: uuid(),
          text: 'Pay Water Bill',
          complete: false
        },
      ],
      showCompletedTodos: true,
      showIncompletedTodos: true
    }

    this.deleteTodo = this.deleteTodo.bind(this)
    this.toggleTodo = this.toggleTodo.bind(this)
    this.toggleShowCompletedTodos = this.toggleShowCompletedTodos.bind(this)
    this.toggleShowIncompletedTodos = this.toggleShowIncompletedTodos.bind(this)
  }

下面是我在子组件中通过 TodoActions.fuctionName 调用的一些函数:

// Toggle the showing of completed todos
toggleShowCompletedTodos() {
    this.setState({
        showCompletedTodos: !this.state.showCompletedTodos
    })
}

// Toggle the showing of incompleted todos
toggleShowIncompletedTodos() {
    this.setState({
        showIncompletedTodos: !this.state.showIncompletedTodos
    })
}

deleteTodo(todoToDelete) {
    this.setState({
        todo: this.state.todos.filter( function(todo) {
            return todo.id !== todoToDelete.id
        })
    })
}

当我触发这个函数时,我得到 Uncaught TypeError: this.setState is not a function

过去在构造函数中将函数绑定到 this 解决了这个问题,但在这个问题中,它不起作用

这是我的参考:

是不是因为它是 Flux store 而不是普通的 class?

看起来好像您是从继承自 EventEmitter 的 class 调用 this.setState,但 this.setState 是组件 class 的一个函数,您不能调用它来自 class 扩展 EventEmitter。