【问题标题】:`this.setState` not a function in a bound function`this.setState` 不是绑定函数中的函数
【发布时间】:2017-06-16 02:56:21
【问题描述】:

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

这是我在助焊剂商店中的构造函数:

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.fctionName 调用的一些函数:

// 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 解决了这个问题,但在这个问题上,它不起作用

这是我的参考: this.setState is not a function

是不是因为它是 Flux store 而不是普通类?

【问题讨论】:

标签: reactjs reactjs-flux


【解决方案1】:

看起来好像您是从继承自 EventEmitter 的类调用 this.setState,但 this.setState 是 Component 类的函数,您不能从扩展 EventEmitter 的类中调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2019-10-25
    • 2020-09-08
    • 2019-08-05
    • 2018-09-22
    相关资源
    最近更新 更多