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

Offen
#2,922 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Vorherrschende Sprache
JavaScript
Sterne
11.8k
Forks
7.9k
Ø Merge
1 T. 11 Std.
Gemergte PRs (30 T.)
11

Beschreibung

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"/>
}

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginnen Sie im Abschnitt Main Concepts der React-Dokumentation, den das Issue als vorgesehenen Einstiegspunkt identifiziert. Erklären Sie, dass bedingtes Rendern mit geänderten props dieselbe Komponente nicht erneut mountet, und dokumentieren Sie den im Issue gezeigten distinct-key approach; abgeschlossen ist die Aufgabe, wenn Verhalten und Lösung für die Leser klar sind.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
javascript, react
Bereich
documentation
Issue-Typ
Dokumentation
Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
42/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.