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

157
Visualizações
this.setState() not changing value (not an asynchronous update issue)

Just a note, this question is NOT an asynchronous update problem (at least, I don't think it is).

I have a class component with the following content (heavily simplified to get right to the issue):

  constructor(props) {
     super(props);
     this.state = {
       aSelected: false;
       bSelected: false
     }
  }

 handleCheckboxChange = (e) => {   
     const { checked, value } = e.target;
    
     console.log( 'checked: ', checked );

     if(value=="a") {
        this.setState( {aSelected: checked}, () =>  {
        console.log('aSelected: ', this.state.aSelected);
        console.log("---")
     });
     }

     if(value=="b") {
        this.setState( {bSelected: checked}, () =>  {
        console.log('bSelected: ', this.state.bSelected);
        console.log("---")
     });
     } 
 }

Somewhere inside the render return, I have this:

<input>
   type="checkbox"
   value="a"
   onChange={this.handleCheckboxChange}
   checked={this.state.aSelected}
   disabled={ (this.state.aSelected || (!this.state.aSelected && !this.state.bSelected) ) ? false : true} 
</input>

<input>
   type="checkbox"
   value="b"
   onChange={this.handleCheckboxChange}
   checked={this.state.bSelected}
   disabled={ (this.state.bSelected || (!this.state.aSelected && !this.state.bSelected) ) ? false : true}
</input>

Here is the output logged in Chrome Developer Tools. As you can see, "checked" is toggled appropriately each time I selected and unselect the checkbox. However, the state of "selected" (should say "aSelected") is never changed and always has the initial state value of false. Anyone know why the value of "selected" (should say "aSelected") is never changed?

Edit: My goal is to create two checkbox items, where the user can only select ONE or select NONE. While one is selected, the other should be disabled.

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you call setState to update the state, React re-renders the component, which resets the checkbox back to it's default (i.e. unchecked) state.

You'll need to use the current state to manage the checkbox as well. The JSX should look something like:

<input
   type="checkbox"
   checked={this.state.aSelected}
   onChange={this.handleCheckboxChange}
/>

In React's terms, this is what's known as a "controlled component" because React is fully responsible for keeping up with the input's state. Read more in the docs here: https://reactjs.org/docs/forms.html#controlled-components vs https://reactjs.org/docs/uncontrolled-components.html

Edit to match the question's edits: In your render function, be sure you're using this.state.aSlected. Note, you also still need the checked={this.state.aChecked} attribute as well, otherwise the checkbox will be unchecked on the next render. Like:

<input
   type="checkbox"
   value="a"
   onChange={this.handleCheckboxChange}
   checked={this.state.aSelected}
   // added for clarification *
   disabled={this.state.aSelected || (!this.state.aSelected && !this.state.bSelected) ? false : true} 
/>

Edit with Working Example Here's a working CodeSandbox example where checking one checkbox disables the other:

class CheckboxComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      aSelected: false,
      bSelected: false
    };
  }

  handleCheckbox = (event) => {
    if (event.target.name === "boxA") {
      this.setState({ aSelected: event.target.checked });
    } else if (event.target.name === "boxB") {
      this.setState({ bSelected: event.target.checked });
    }
  };

  render() {
    let aDisabled = this.state.bSelected && !this.state.aSelected;
    let bDisabled = this.state.aSelected && !this.state.bSelected;

    return (
      <div>
        <label>
          <input
            type="checkbox"
            name="boxA"
            checked={this.state.aSelected}
            onChange={this.handleCheckbox}
            disabled={aDisabled}
          />
          Checkbox A
        </label>
        <br />
        <br />
        <label>
          <input
            type="checkbox"
            name="boxB"
            checked={this.state.bSelected}
            onChange={this.handleCheckbox}
            disabled={bDisabled}
          />
          Checkbox B
        </label>
      </div>
    );
  }
}
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