【发布时间】: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