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

178
Visualizações
Array.splice not woking when there is one index left

My idea in the code is to handle and store the change on checkbox in array when I uncheck one of the checkboxs It will splice and remove its index. The problem is it will not remove the last index even when it's checkbox is unchecked and its value is false.

The code:

 CheckBoxHandler1(e) {
    let temp = [...this.state.boxes];
    console.log(e.target.checked);
    e.target.checked === false
      ? temp.splice(e.target.value, 1)
      : (temp[e.target.value] = [e.target.checked, e.target.name]);

    this.setState({ boxes: temp, checked: e.target.checked });
    console.log(temp);
    console.log(this.state.boxes);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should probably be storing the state of all the boxes rather than removing them. You can initially start off with an empty object for the array and then update that when each box changes.

const { useEffect, useState } = React;

function Example() {

  const [ boxes, setBoxes ] = useState({});

  // The `handleChange` is on the parent element
  // so we need to extract the nodeName, the name of
  // the checkbox, and it's status, and then if we've
  // actually un/checked a box, update the state.
  function handleChange(e) {
    const { nodeName, checked, name } = e.target;
    if (nodeName === 'INPUT') {
      setBoxes({ ...boxes, [name]: checked });
    }
  }

  // This just confirms the state has been updated
  useEffect(() => console.log(boxes), [boxes]);

  return (
    <div onChange={handleChange}>
      Name: <input name="name" type="checkbox" checked={boxes.name} />
      Age: <input name="age" type="checkbox" checked={boxes.age} />
      Job: <input name="job" type="checkbox" checked={boxes.job} />
    </div>
  );

};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Class component:

const { Component } = React;

class Example extends Component {

  constructor() {
    super();
    this.state = {};
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    const { nodeName, checked, name } = e.target;
    if (nodeName === 'INPUT') {
      this.setState({ ...this.state, [name]: checked }, () => {
        console.log(this.state)
      });
    }
  }

  render() {
    return (
      <div onChange={this.handleChange}>
          Name: <input name="name" type="checkbox" checked={this.state.name} />
          Age: <input name="age" type="checkbox" checked={this.state.age} />
          Job: <input name="job" type="checkbox" checked={this.state.job} />
      </div>
    );
  }

};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></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