【问题标题】:Behaviour of arrow functions outside an ES6 React class constructorES6 React 类构造函数之外的箭头函数的行为
【发布时间】:2017-11-21 20:03:51
【问题描述】:

我在一个项目中有一段简单的代码,使用 react + react-redux 和 es6(通过 babel):

class HomeScreen extends React.Component {
  // problematic piece of code: 
  showLockTimer = setTimeout(this.authenticate, 2000);

  leaveAnimationTimer = setTimeout(() => {
     this.setState({ hide: true }); // setState is correctly called
  }, 1000);

  authenticate = () => { // Never runs.
    // do some stuff...
    this.props.showLock();
  } 
}

由于某种原因,从不调用 authenticate 方法...但是如果我将 setTimeout 放在类构造函数中,它就可以工作:

class HomeScreen extends React.Component {
  // This is the only changed code:
  constructor(props) {
    super(props);
    this.showLockTimer = setTimeout(this.authenticate, 2000);
  }

  leaveAnimationTimer = setTimeout(() => {
     this.setState({ hide: true }); // setState is correctly called
  }, 1000);

  authenticate = () => { // Now it runs!
    // do some stuff...
    this.props.showLock();
  } 
}

我以为我很了解this 绑定,带有箭头功能,但我不明白为什么会这样?我试图用谷歌搜索很多关于这个问题的内容,也阅读了关于 SO 的类似问题,但似乎找不到任何解释它的东西。

对不起,如果这是一个重复的问题。

【问题讨论】:

  • 在第一个例子中,将authenticate方法移到ShowLockTimer上方

标签: javascript reactjs ecmascript-6 react-redux arrow-functions


【解决方案1】:

在第一个示例中,您甚至在 this.authenticate 存在之前就使用了它。将其包装在另一个箭头函数 () => {this.authenticate()} 中即可完成这项工作

【讨论】:

  • 天哪...我不敢相信它这么简单!那么,我在 javascript 中定义类方法的顺序很重要吗?最后发生的事情是只有在对象使用其方法初始化后才调用构造函数?
  • 类方法可以按任何顺序定义,但这些不是类方法,它们是公共类字段。类主体中的 foo = ... 之类的属性就像它们在 super() 所在的类构造函数中一样运行,因此顺序很重要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 2018-06-28
  • 2019-01-06
  • 1970-01-01
  • 2018-11-29
相关资源
最近更新 更多