0

我使用反应+反应-终极版用ES6(通过巴别)有一个简单的代码中的一个项目:行为的ES6外箭头官能团反应类构造

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(); 
    } 
} 

出于某种原因,该验证方法不会被调用......但是,如果我把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结合得很好,带箭头的功能,但我不明白为什么没有他的发生?我试图谷歌很多这个问题,也阅读了类似的问题,但似乎无法找到任何解释它。

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

+1

在第一个例子中,移动'验证'方法上面'ShowLockTimer' – Krizzu

回答

2

在第一个示例中,在它存在之前使用this.authenticate。用另一个箭头函数() => {this.authenticate()}包装它将使这项工作

+0

哦,我的......我简直不敢相信它!那么,我在JavaScript中定义类方法的顺序很重要? 最后发生了什么是构造函数仅在对象使用其方法初始化后才调用? – andredp

+1

可以按任意顺序定义类方法,但这些不是类方法,它们是公共类字段。在类体中像'foo = ...'这样的属性就像super()所在的类构造函数一样运行,所以排序很重要。 – loganfsmyth