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

203
Visualizações
ReactJs conditional rendering not working

I am trying to call the onLogin() function from a child called Login. This function will set the state based on which the conditional rendering is done.

The problem is that Home is not getting rendered after setState is called. In fact the function getView() is not getting called after calling setState(), although the view is updated after i refresh the page.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.onLogin.bind(this);
    this.state = {userLoggedIn: !!localStorage.getItem(USER_NAME)};
  }

  onLogin() {
    this.setState({userLoggedIn: true});
  }

  getView() {
    return this.state.userLoggedIn ? <Home /> :  <Login onLogin={this.onLogin} />;
  }

  render() {
    return (
        <span>
          {this.getView()}
        </span>
    );
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to add .bind(this) where you pass the prop to Login component like this:

<Login onLogin={this.onLogin.bind(this)} />

and you can delete the line after super(props); Here is a link to codesandbox: https://codesandbox.io/s/boring-chaum-5l8k6?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't seem to have bound getView method like you did for onLogin. To avoid binding issues maybe just use arrow functions like so

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {userLoggedIn: !!localStorage.getItem(USER_NAME)};
  }

  const onLogin = () => {
    this.setState({userLoggedIn: true});
  }

  const getView = () => {
    return this.state.userLoggedIn ? <Home /> :  <Login onLogin={this.onLogin} />;
  }

  render() {
    return (
        <span>
          {this.getView()}
        </span>
    );
  }
}
about 4 years ago · Juan Pablo Isaza 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