React this 指向问题

React this 指向问题

  • 在 Class 里面使用, this.setState()
    • 报错: Cannot read property 'setState' of undefined
  1. 在 constructor 里面添加绑定
constructor(props) {
  // ...
  this.fn = this.fn.bind(this)
}
  1. 绑定方法的时候使用箭头函数

  1. 注册方法的时候使用箭头函数
fn = () => {
  // some code
}

你可能感兴趣的:(React this 指向问题)