技術と魚

雑感と備忘録

getDerivedStateFromPropsでthisがundefinedな件

という問題に直面しました。GitHubのissueをたどってみると、

I understand this might seem a bit overprotective. But I don’t see practical upsides to allowing it. And I see downsides: this will be there, it will just point to a different thing, and confuse anyone who doesn’t know JS deeply.

https://github.com/facebook/react/issues/12612#issuecomment-381332338

ちょっと過剰な防衛だと思うけど、もしthisがあると、JSをよく知らない人からすると異なるthisが参照されるから混乱のもとになる

だそう。 しかし、よく知っている人からしたらstaticのthisはconstructorになってくれるのが普通でしょ?逆に混乱の元になるよ、みたいなコメントもあります。

一部コンポーネントで継承を使っていたから、thisが機能しないとかなり困るなあと思ったので、以下のハックを思いついた。無論正規の方法ではないので推奨はしません。

static get getDerivedStateFromProps() {
  return (props, state) => {
    // ここならthisはconstructorになる
  };
}