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

これは

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

ガイドのリンク

ja.reactjs.org

高階 (Higher-Order) コンポーネント

横断的関心事に HOC を適用する

コンポーネントの利用についてこれまで通りできないパターンも起こりうる。

HOC は入力のコンポーネントを改変したり、振る舞いをコピーするのに継承を利用したりしません。むしろ HOC は元のコンポーネントをコンテナコンポーネント内にラップすることで組み合わせるのです。HOC は副作用のない純関数です。

らしい。
従来は横断的なものについてはミックスインを使うようにしてきていたけれど、HOCを使うのも便利だよという事と解釈した。

// This function takes a component...
function withSubscription(WrappedComponent, selectData) {
  // ...and returns another component...
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.handleChange = this.handleChange.bind(this);
      this.state = {
        data: selectData(DataSource, props)
      };
    }

    componentDidMount() {
      // ... that takes care of the subscription...
      DataSource.addChangeListener(this.handleChange);
    }

    componentWillUnmount() {
      DataSource.removeChangeListener(this.handleChange);
    }

    handleChange() {
      this.setState({
        data: selectData(DataSource, this.props)
      });
    }

    render() {
      // ... and renders the wrapped component with the fresh data!
      // Notice that we pass through any additional props
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };
}

例もいくつか載っていて説明も不思議な日本語だったりするのを除けば結構わかりやすい。

あまり集中できてない気がする。今日はここまで。