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

Aperta
#2,922 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
JavaScript
Stelle
11.8k
Fork
7.9k
Merge medio
1g 11h
PR unite (30g)
11

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia dalla sezione Main Concepts della documentazione di React, che l’issue identifica come punto di ingresso previsto. Spiega che il rendering condizionale con props modificate non esegue il remount dello stesso componente, e documenta il distinct-key approach mostrato nell’issue; il lavoro è completato quando il comportamento e la soluzione sono chiari ai lettori.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
javascript, react
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
42/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.