Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Issue storing ref elements in loop

When trying to store refs in an array inside a loop, I get weird results when the page re-renders (everything is as expected when the page first renders).

I reproduced the problem in this very small jsfiddle: https://jsfiddle.net/69z2wepo/68251/

class Hello extends React.Component {
  constructor(props) {
      super(props);

      setTimeout(() => { this.setState({foo: 'bar'}); }, 1000);
  }

  render() {
    console.log('--- RENDER ---');

    const divs = [];
    this.elements = [];

    for (let i = 1; i <= 2; i++) {
        divs.push(
            <div
                key={i}
                ref={(ref) => {
                    this.elements.push(ref);

                    console.log(this.elements);
                }}
            >
            </div>
        );
    }

    return (
        <div>
            {divs}
        </div>
    );
  }
}

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

You can see that when the page renders a second time, I suddenly get null values and end up with an array of 4 elements.

Could anyone explain why it behaves like that? Why is the function handling the ref executed 4 times after the second rendering?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

From the documentation:

React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

So the reason why four ref callbacks are called is because two components are unmounted and two are mounted.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda