LoginSignup
0
0

More than 1 year has passed since last update.

setTimeoutの中でthis.stateがundefinedになるときの対処法

Posted at
console.log(this.state);  // 正しく取得できる
setTimeout(function () {
  console.log(this.state);  // undefined
}, 1000);

【結論】thisを確定させる

setTimeout内では、関数の呼び出し元がグローバルオブジェクトになるので、thisを確定させる必要があります。

.bind(this)を使う

setTimeout(function () {
  console.log(this.state);  // 正しく取得できる
}.bind(this), 1000);

アロー関数を使う


setTimeout(() => {
  console.log(this.state);  // 正しく取得できる
}, 1000);

参考文献
https://qiita.com/mejileben/items/69e5facdb60781927929

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0