React中的函数声明'this'范围

时间:2019-06-02 12:04:27

标签: javascript reactjs

为什么提取图像按钮onClick函数可以在函数表达式中使用,而不能在同一调用方法中使用函数声明。

class FetchButtom extends Component {

 async fectchImage() {
    const IMAGE_API = 'Some Image API';
    try {
      const images = await fetch(IMAGE_API);
      const json = await images.json();
      console.log(this);
      this.props.addImage(json.items);
    } catch (error) { }
  }

 fectchImageExpression = async () => {
    const IMAGE_API = 'Some Image API';
    try {
      const images = await fetch(IMAGE_API);
      const json = await images.json();
      console.log(this);
      this.props.addImage(json.items);
    } catch (error) { }
  }

 render() {
    return (
      <div>
        <button 
          // console.log(this); -> this point to FetchButtom
          onClick={() => this.fectchImage()}
          // This will no trigger fectchImage runs
          onClick={() => this.fectchImage}
          // TypeError: Cannot read property 'props' of undefined
          onClick={this.fectchImage}

          // Working perfectly, same as onClick={() => this.fectchImage()}
          onClick={() => this.fectchImageExpression()}
          // This will no trigger fectchImageExpression runs
          onClick={() => this.fectchImageExpression}
          // Working perfectly, same as onClick={() => this.fectchImage()}
          onClick={this.fectchImageExpression}
        >
          Fetch image
        </button>
      </div>
    );
  }
}

所以,我的问题是为什么函数表达式使这2种情况在{() => this.fectchImageExpression()}{this.fectchImageExpression}函数声明中仅在{{1 }}

2 个答案:

答案 0 :(得分:1)

  • 为什么起作用:
    使用箭头功能,对于属性表达式也是如此,
    您正在用词法(从周围的声明上下文)严格绑定 this

  • 为什么不起作用:
    不同的是,您将从调用该函数的作用域中继承 this ,而您将丢失这些方法。

答案 1 :(得分:0)

onClick收到一个函数声明-() => this.fectchImage()是一个匿名函数,被调用时将运行this.fectchImage。 将this.fectchImageExpression分配给onClick时,您将传递函数而不运行它,而单击该函数将运行传递的this.fectchImageExpression

当您将onClick分配给() => this.fectchImageExpression时,这是一个匿名函数,仅具有对this.fectchImageExpression的引用,但没有调用它。因此,似乎它什么也没做。