小心 this 的指向

react组件中,特别要小心this的使用。比如,在Counter那个示例中,我们使用以下方式声明incrementdecrement方法:

import React, { Component } from "react"
import ReactDOM from "react-dom"

class Counter extends Component {

  state = {
    count: 0,
  }

  increment() {
    this.setState({
      count: this.state.count + 1
    })
  }

  decrement() {
    this.setState({
      count: this.state.count - 1
    })
  }

  render() {
    return (
      <div>
        <h1>一共点击了{this.state.count}次</h1>
        <input type="button" value="+" onClick={this.increment.bind(this)} />
        <input type="button" value="-" onClick={this.decrement.bind(this)} />
      </div>
    )
  }
}

ReactDOM.render(<Counter />, document.querySelector("#root"))

这时,点击按钮之后,控制台抛出以下异常:

《小心 this 的指向》

导致这个异常的原因,实际就是this的指向问题

《小心 this 的指向》

解决方案是将this的指向固定下来,最简单的方式就是通过箭头函数来声明方法。

increment = () => {
    this.setState({
        count: this.state.count + 1
    })
}

decrement = () => {
    this.setState({
        count: this.state.count - 1
    })
}

使用箭头函数的方式来声明方法,函数中的this指向函数声明时所在的作用域。因此,incrementdecrement函数中的this就会一直指向当前Counter产生的实例,即使是传递给input元素来调用。

除了使用箭头函数固化this以外,还可以使用bind方法,在声明函数时,依然使用普通函数:

increment() {
    this.setState({
        count: this.state.count + 1
    })
}

decrement() {
    this.setState({
        count: this.state.count - 1
    })
}

绑定函数的时候,我们需要可以使用bind方法,将当前的作用域绑定到函数上:

<input type="button" value="+" onClick={this.increment.bind(this)} />
<input type="button" value="-" onClick={this.decrement.bind(this)} />

这两种方法都可以用来固化this

    原文作者:佛也要生活
    原文地址: https://segmentfault.com/a/1190000017569866
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞