Qiitaからの移植です。
はじめに
emoji-martは、下の画像のように絵文字選択フォームを実現するReactコンポーネントです。
このコンポーネントを実際に利用していたら、次のような警告文がJavaScriptのコンソールに表示されました。
Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details. * Move data fetching code or side effects to componentDidUpdate. * If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state * Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder. Please update the following components: NimblePicker
NimblePicker
コンポーネントでReact 17で廃止予定のメソッドcomponentWillReceiveProps
が使われていて、このままだとemoji-martはReact 17で使用できなくなります。 詳細はReact公式ブログの記事に記載されています。
自分がこの問題に気付いたときはReact初心者でした。なので、とりあえずissueを作って、これを見た誰かに直してもらおうと思いました。しかし、2ヶ月が経っても直される気配がありませんした。
これはまずいと思って、自分で改修できないと決意しました。2ヶ月間Reactを触り続けてReactの理解度が上がっていたので、自分で改修できるのではないかという自信が生まれていました。
改修内容
実際に出したPRはこちらです。
Qiitaの記事『React.js のライフサイクルメソッド componentWillReceiveProps の廃止対応』を参考しながら、改修方法を考えました。Nimble Picker
のcomponentWillReceiveProps
ではprops
から新しいstate
を作っています。なので、今回は記事中の2番目の方法「getDerivedStateFromProps に置き換える」方法をで採用しました。
今気付いたこと
getDerivedStateFromProps
ではstateの変更箇所だけを返せばいいので、
static getDerivedStateFromProps(props, state) { if (props.skin) { return { skin: props.skin } } else if (props.defaultSkin && !store.get('skin')) { return { skin: props.defaultSkin } } return null }
の方が適切でしたね。