reactjs / reactjs/react.dev

Docs regarding setState are in direct conflict with one another

Aperta
#3,692 2 commenti 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

In Introducting Hooks, and several other places, there is a simple counter example that illustrates how to use the useState hook.

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

However, there happens to be another counter example in the Hooks API Reference for useState.

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}

In this second example, a callback is being passed into the setState function, and the code is accompanied by the following language...

The ”+” and ”-” buttons use the functional form, because the updated value is based on the previous value.

This would imply that the first example (which is in a very prominent location in the docs by the way), is actually incorrect and is encouraging an anti-pattern.

I hope you can see how these two examples are in direct conflict with one another and might be causing confusion in the community!

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

Leggi gli esempi di contatori in Introducing Hooks e Hooks API Reference, in particolare la sezione functional-updates, e confronta le indicazioni relative a setState. Risolvi l’incoerenza in modo che la documentazione fornisca una spiegazione chiara di quando sia appropriata ciascuna forma, quindi verifica che gli esempi collegati e il testo circostante non siano più in conflitto.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.