箭头函数在 ES6 React class 构造函数之外的行为
Behaviour of arrow functions outside an ES6 React class constructor
我在一个使用 es6 的 react + react-redux 的项目中有一段简单的代码(通过 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 构造函数中,它会起作用:
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
绑定,带有箭头功能,但我不明白为什么会这样?对于这个问题,我尝试 google 很多,并且还在 SO 上阅读了类似的问题,但似乎找不到任何解释它的东西。
抱歉,如果这是一个重复的问题。
在第一个示例中,您甚至在 this.authenticate
存在之前就使用了它。将它包装在另一个箭头函数 () => {this.authenticate()}
中将使它工作
我在一个使用 es6 的 react + react-redux 的项目中有一段简单的代码(通过 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 构造函数中,它会起作用:
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
绑定,带有箭头功能,但我不明白为什么会这样?对于这个问题,我尝试 google 很多,并且还在 SO 上阅读了类似的问题,但似乎找不到任何解释它的东西。
抱歉,如果这是一个重复的问题。
在第一个示例中,您甚至在 this.authenticate
存在之前就使用了它。将它包装在另一个箭头函数 () => {this.authenticate()}
中将使它工作