setState()

5736 ワード

setState()のReact公式ドキュメント
setState()の詳細についての公式ドキュメント

演技を習う

this.setState()と出会う.
htmlでレンダリングされた要素では、この方法は、変更可能なthis.stateに格納されているすべての要素の値を変更するための関数と見なすことができる.
でもこれ.setState()にはいくつかの使い方があるようで、覚えておくためにメモしておきます.

いくつかの使い方


syntax

this.setState(updater,[callback])まず、setStateはインスタントの명령ではなく、요청です.
したがって、すぐに更新するわけではありません.
incrementCount() {
  // Note: this will *not* work as intended.
  this.setState({count: this.state.count + 1});
}

handleSomething() {
  // Let's say `this.state.count` starts at 0.
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();
  // When React re-renders the component, `this.state.count` will be 1, but you expected 3.

  // This is because `incrementCount()` function above reads from `this.state.count`,
  // but React doesn't update `this.state.count` until the component is re-rendered.
  // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.
したがって,以上のコードの結果値は1である.

updater


updaterの構文は次のとおりです.(state, props) => stateChange
  • state stateは、変更が有効になる前の状態を示し、このときの状態は常に前の値が反映値であることを保証する.
    したがって、次のような行為は予想通りに行われる.
  • incrementCount() {
      this.setState((state) => {
        // Important: read `state` instead of `this.state` when updating.
        return {count: state.count + 1}
      });
    }
    
    handleSomething() {
      // Let's say `this.state.count` starts at 0.
      this.incrementCount();
      this.incrementCount();
      this.incrementCount();
    
      // If you read `this.state.count` now, it would still be 0.
      // But when React re-renders the component, it will be 3.
    }