反应-箭头函数错误(建议类字段)

时间:2019-07-10 22:32:01

标签: javascript reactjs

这些正在起作用

        .AddClasses(f => f.Where(t => t != typeof(RealUserAIProvider)))
        .AsSelfWithInterfaces().WithScopedLifetime());
constructor(props) {
    super(props);
    this.state = {
      hello: this.hello()
    };

    this.hello = this.hello.bind(this);
  }

  hello() {
    return 'hello';
  }
 constructor(props) {
    super(props);
    this.state = {
      hello: this.hello()
    };
  }

  hello = () => {
    return 'hello';
  };

这不是

state = {
    hello: this.hello()
  };

  hello() {
    return 'hello';
  }

我不明白。第三个示例甚至无法访问“ this”(包括道具) 这样写状态时,应该如何在状态中使用绑定函数,为什么它不起作用?

这是我收到的错误(控制台中未显示成功,但在网站上显示)

TypeError:this.hello不是函数

app / src / Page.js:11    8 | };    9 |   10 |状态= {

  

11 |您好:this.hello()        | ^ 12 | };     13 |     14 |你好=()=> {

1 个答案:

答案 0 :(得分:3)

当这些类属性被编译时,它们将按照其写入顺序移动到构造器的末尾。 。所以当您这样做时...

class Example {
  state = {
    hello: this.hello()
  }; 

  hello = () => {
    return 'hello;
  };
}

...它大致被翻译成这样:

class Example {
  constructor() {
    this.state = {
      hello: this.hello()
    };

    this.hello = () => {
      return 'hello;
    };
  }
}

在此已编译的代码中,您试图在定义this.hello之前访问this.hello,从而收到错误。相反,您需要更改顺序,以便先定义函数,然后再使用它。

class Example {
  hello = () => {
    return 'hello;
  };

  state = {
    hello: this.hello()
  }; 
}
相关问题