reactjs / reactjs/react.dev

Use a better example for Effect hook

Offen
#1,805 6 Kommentare 3 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

The following example is used in:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

This example creates confusion because the example doesn't actually need useEffect to operate correctly.

If you set document.title outside of the useEffect, the app behaves exactly the same.


Suggested changes

  • Use an example which would not work correctly if it wasn't placed in a useEffect. It should be something that depends on the DOM having been updated. Maybe setting the document.title to a document.getElementById or something like that. This would also be a contrived/useless example. Something practical would be better.

  • Show the lifecycle of useEffect early. I was most interested in the lifecycle of when this method is called. In Dan's recent blog post on effects, this is the first thing that is covered, and it should be the same for these docs.

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

Beginne mit den Effect-Hook-Beispielen in hooks-overview.html#effect-hook und hooks-effect.html und vergleiche dann das aktuelle Beispiel mit der Lifecycle-Diskussion in der referenzierten Dokumentation. Ersetze das verwirrende Beispiel durch eines, das zeigt, warum useEffect benötigt wird, und führe seinen Lifecycle früher ein; als erledigt gilt die Aufgabe, wenn beide Seiten das Verhalten einheitlich erklären und das verbesserte Beispiel zeigen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
javascript, react
Bereich
documentation
Issue-Typ
Dokumentation
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
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.