Я стараюсь понять, как this
работает в классах ES6, что затрудняет создание приложений с любой консистенцией. Вот один пример моего замешательства в React классе:Объем `this` в классах ES6
class Class extends React.Component {
constructor() {
super();
this.state = {
timeout: 0
}
}
componentWillMount() {
// Register with Flux store.
// On change run this._storeUpdated()
}
_storeUpdated() {
if (this.state.timeout < 3) {
console.log(this.state.timeout); // 0
setTimeout(() => {
this.setState({
authorized: false,
timeout: this.state.timeout + 1 // undefined?
});
// Force Flux store to update - re-runs this method.
}, 1000)
}
}
}
Почему this.state.timeout undefined
в вызове setState()
? Однако, если я стрелка функционировать метод, то он работает:
_storeUpdated =() => {
if (this.state.timeout < 3) {
console.log(this.state.timeout); // 0
setTimeout(() => {
this.setState({
authorized: false,
timeout: this.state.timeout + 1 // 1
});
// Force Flux store to update - re-runs this method.
}, 1000)
}
}
Что на самом деле происходит?
Как именно вы его вызываете? – zerkms
Внутри компонентаWillMount –
(с использованием Flummox) 'Flux.getStore ('store'). On ('change', this._storeUpdated);' –