reactjs / reactjs/react.dev

Please explain in the main concepts that react doesn't refire componentDidMount even with conditional rendering and the solution is to use different keys

オープン
#2,922 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
11

説明

As said by someone else here: "This should be way more obvious in the React documentation. This achieved exactly what I was after, but took hours to find."

This also took me hours to find that react doesn't automatically re-mount a component if the code is similar but just props change.

I was using conditional rendering doing:

var mycode = ""
if(a==true) {
      mycode = <MyComponent myvar="true"/>
} else {
      mycode = <MyComponent myvar="false"/>
}

And was expecting componentDidMount to fire to do crucial stuff, which obviously doesn't happen unless you specify a different key for both (solution at the bottom).

Please make this part of the Main Concepts of the React doc. The above linked answer got +190 upvotes which shows that this is a real problem for many coders.

Thank you very much for your consideration

Solution:

var mycode = ""
if(a==true) {
      mycode = <MyComponent myvar="true" key="1"/>
} else {
      mycode = <MyComponent myvar="false" key="2"/>
}

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

React ドキュメントの Main Concepts セクションから始めます。issue ではここが意図された入口として示されています。props が変更された条件付きレンダリングでは同じコンポーネントが再マウントされないことを説明し、issue に示されている distinct-key approach を文書化します。読者に動作と解決策が明確に伝われば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
42/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。