reactjs / reactjs/react.dev

Docs regarding setState are in direct conflict with one another

Aberta
#3,692 2 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Linguagem predominante
JavaScript
Estrelas
11.8k
Forks
7.9k
Merge médio
1d 11h
PRs com merge (30d)
11

Descrição

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!

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Leia os exemplos de contadores em Introducing Hooks e Hooks API Reference, especialmente a seção functional-updates, e compare as orientações sobre setState. Resolva a inconsistência para que a documentação forneça uma explicação clara de quando cada forma é apropriada e, em seguida, verifique se os exemplos vinculados e o texto ao redor não entram mais em conflito.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
javascript, react
Domínio
documentation
Tipo de issue
Documentação
Dificuldade
3/5
Tempo estimado
1-2 dias
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
35/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.