Reactガイドを読んでいくその250

これは

Reactのガイドを読んでいく記事です。

ガイドのリンク

ja.reactjs.org

クリーンアップを必要としない副作用

ReactがDOMを更新したあとで追加のコードを実行したいという場合があるので例を見ていく。

クラスを使った例

Reactのクラスコンポーネントではrenderメソッド自体が副作用を起こすべきではない。
ReactがDOMをこうしんした後に実行するとよい。

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }

を二回書かないといけない点に注意が必要。
次回はフックで書いた時にどうなるかを見ていく。

今日はここまで。