0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【React】this.setStateの即時反映

Posted at

困ったこと

Formの入力欄をリアルタイムでバリデーションしたいけど,this.setStateが即時に反映されない.

.js
class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      foo: 1
    };
  }
  
  foo_setTwo = () => {
    this.state({ foo: 2 });
    console.log(foo); // foo : 1
  }
}

解決法

コールバックで呼び出すか,reactのライフサイクルでcomponentDidUpdateメソッドを使うか.

.js
  foo_setTwo = () => {
    this.state({ foo: 2 }, () => {
      console.log(foo); // foo : 2
    });
  }

  componentDidUpdate(prevProps, prevState, snapshot){
    console.log(this.state.foo); // foo : 2
  }
0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?