https://qiita.com/ShinKano/items/0a3d7b4c040fc7073bd8

とにかくコンポーネントをリセットしたい!マウントからやり直したい! という時に使えるテクニックを紹介します。

初期化したいコンポーネントのpropskeyを設定し、keyを更新します。

const Component = () => {
  return (
    <div key={something}>
      ...
    </div>
  )
}

説明

コンポーネントにはライフサイクルがあります。

Reactコンポーネントはとても賢いので、うまく差分を計算してコンポーネントは不要な再描画が走らないようにしています。

そのため、マウント後の更新に関しては基本的にUpdateが適用されます。

一方でkeyはコンポーネントの一意性を保つための仕組みですので、keyが更新されるという事は、まるっきり新しいコンポーネント扱いになります。

そのため、Updateではなく、Mountから新規で描画できる、というわけです。

Why not register and get more from Qiita?

  1. We will deliver articles that match youBy following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficientlyBy "stocking" the articles you like, you can search right away

What you can do with signing up

Sign up

Login