ES6でReact.ComponentのisMounted()が使えない問題の代替方法

プログラミング#React#ES6
t-hiroyoshi
t-hiroyoshi
2015年10月15日 投稿
image.png (873.0 kB)

こんにちは、t-hiroyoshiです。
最近はReactやreduxを使ってUIを開発しているのですが、両方ともガンガン更新されていくので追いかけるのがとても楽しい日々を過ごしています。

突然ですが、Reactで開発していて次のようなWarningを見たことはありませんか?

warning
Warning: setState(...): Can only update a mounted or mounting component.
This usually means you called setState() on an unmounted component.
This is a no-op. Please check the code for the undefined component.

これはUnmountされたコンポーネントのsetState()を呼んだ時に出るもので、回避する方法があります。

その回避方法はReact.ComponentAPIのisMounted()を使いUnmountされたコンポーネントへの処理を回避することです。
isMounted()はそのコンポーネントがmountされている時はtrue、そうでない時はfalseを返してくれるので非同期処理などでUnmountされたコンポーネントに対するsetState()fourceUpdate()を防ぐ事が可能になります。

がしかし、なんとES6のclassを使ってReactを書いているとisMounted()は使えません!
なのでその簡単な代替方法を紹介します、それはコンポーネントのstateでisMountedを持つ方法です。

jsx
import React from "react";

class Something extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isMounted: false,
      word: "foo"
    };
  }

  componentDidMount() {
    this.setState({ isMounted: true });
  }

  componentWillUnmount() {
    this.setState({ isMounted: false });
  }

  someAction() {
    const { isMounted } = this.state;

    // UnmountされていたらsetStateしない。
    if (isMounted) {
      this.setState({ word: "bar" });
    }
  }

  render() {
    // …
  }
}

このようにする事でUnmountされたコンポーネントへのsetState()forceUpdate()をES6でも防ぐ事ができます。

参考リンク