ES6 クラス内でがどのように機能するかを理解するのに苦労しているthis
ため、あらゆる種類の一貫性を備えたアプリケーションを構築することが難しくなっています。React クラス内での私の混乱の一例を次に示します。
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)
}
}
}
undefined
への呼び出し内にthis.state.timeout があるのはなぜ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)
}
}
ここで実際に何が起こっているのですか?