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

172
Visualizações
Javascript instance variable didn't get rendered in React class component when calling setState

A react class component is mounted to html root node. It has two react element h1 tag in its body. One h1 element is directly render inside the render method. Another h1 is decleared in React component class and passed into Render function as a variable.

import React, { Component } from "react";

export default class Test extends Component {
  state = {
    count: 0,
  };

  current_count = (<h1>current count is {this.state.count}</h1>);

  render() {
    return (
      <>
        {this.current_count}
        <h1>current count is {this.state.count}</h1>
        <button
          onClick={() => {
            this.setState({ count: this.state.count + 1 });
          }}
        >
          click me
        </button>
      </>
    );
  }
}

When I clicked the button, it should increase the count, only the react element h1 inside the render function will updated with it's state content.

The following photo is shown the second h1 tag showing count is 4 when I clicked the button 4 times.

enter image description here

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

0

Your current_count is a property that gets created in the constructor, before mount, and only then. Your current code is like

export default class Test extends Component {
  constructor() {
    this.state = {
      count: 0,
    };
    this.current_count = (<h1>current count is {this.state.count}</h1>);
  }

And the constructor only runs once.

You'll need some other method to update it. The best way would be to only generate the JSX on render - perhaps have a function instead that returns the <h1>.

class Test extends React.Component {
  state = {
    count: 0,
  };

  getCurrentCount() {
    return (
      <h1>current count is {this.state.count}</h1>
    );
  }

  render() {
    return (
      <React.Fragment>
        {this.getCurrentCount()}
        <h1>current count is {this.state.count}</h1>
        <button
          onClick={() => {
            this.setState({ count: this.state.count + 1 });
          }}
        >
          click me
        </button>
      </React.Fragment>
    );
  }
}

ReactDOM.createRoot(document.querySelector('.react')).render(<Test />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>

about 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