Next.jsを使っていてgetInitialProps()内でContext APIを使いたかったけど、Reactライフサイクル内にないため使えなかった。
じゃあpropsを経由してconstructor()内でコンテクストに入れようとしたら中身にアクセスできなかった。
componentDidMount()でも悪くはないけどrender()前に処理したいので、ドキュメントにない方法で使ってみます。
まずはソースの要点を見てみます。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import React from "react"; import { Context } from "../context"; class Page extends React.Component { static contextType = Context; constructor(props) { super(props); console.log(this.context); //undefined } render() { const { props, context: { state } } = this; //render内は問題ない return <div>...</div>; } } export default Page; |
Reactライフサイクル内でもコンストラクタ内でthis.contextが使えないことに気づきました。
ドキュメントのconstructor()やClass.contextTypeを見てもできそうにない。
ただソースコードを見るとできそうな感じがある。
第2引数にcontextを指定することでconstructor()内で参照できます。
一応thisで使えるようにsuperにも渡しておきます。
|
1 2 3 4 |
constructor(props, context) { super(props, context); this.context.dispatch({...}) } |
これでgetInitialProps()で処理した値を描画前にcontextに入れれました。
最初はなんでドキュメントにないんだと思いましたが、そもそもconstructor()でcontextにアクセスするケースがほとんどない気がする。通常のReactで考えると必要な状況が思いつかない。
まぁできるんなら使ってやろうって感じですがどっかで問題が出ないかだけは心配。