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

253
Visualizações
React: Logging state of a parent from a child component yields different results

I am trying to develop a component that has two columns: one from which you can add something to a list, and the other one in which you can see/modify items which are already added. I wanted to create a function that deletes the element from the list using splice(index, 1), however, it was always deleting elements from an index to the end. I started debugging it, and I have a problem that I cannot solve. I pass a function as a prop that is suppose to log all elements in a state of a parent component. Here is my code:

const ElementCreator = () => {
  const [elements, setElements] = useState([]);

  const addElement = () => {
    const elementsSlice = elements.slice();
    const newElement = (
      <Example
        position={elements.length}
        deleteHandler={handleElementDelete}
        key={elements.length}
      />
    );
    elementsSlice.push(newElement);
    setElements(elementsSlice);
  };

  const handleElementDelete = (position) => {
    console.log(elements);
  };

  return (
    <Row>
      <Col>
        <Button onClick={addElement}>Add Example Element</Button>
      </Col>
      <Col>
        <div>{elements}</div>
        <Button
          onClick={() => {
            setElements([]);
          }}
        >
          Reset
        </Button>
      </Col>
    </Row>
  );
};

const Example = (props) => {

  return (
    <div>
      {props.position}
      <div>
        <Input type="checkbox" />
        <Input type="checkbox" />
        <Input type="checkbox" />
      </div>
      <div>
        <Button
          onClick={() => {
            props.deleteHandler(props.position);
          }}
        >
          Delete
        </Button>
        <Button>Move Up</Button>
        <Button>Move down</Button>
      </div>
    </div>
  );
};

Anytime I press the delete button, I get a different results. Here is how the console output looks like when I press each button:

[]
react_devtools_backend.js:4049 [{…}]
react_devtools_backend.js:4049 (2) [{…}, {…}]
react_devtools_backend.js:4049 (3) [{…}, {…}, {…}]
react_devtools_backend.js:4049 (4) [{…}, {…}, {…}, {…}]

Can someone tell me why logging the same thing yields different result in each case?

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

0

There are a couple issues with this code..

#1 you are assigning a variable to an array with an empty slice called on it (this could introduce bugs, and not sure why you would need to call this empty function) #2 you are passing the length of the array, then you are wanting to delete something based on the position variable that is tied to the length of that array.

Array length != the last index of an array

arr = [0,1,2,3] => arr has a length of 4, but if you called arr[4] you would get undefined

You say you are clicking on the add button, your function is doing exactly what it is supposed to be doing => adding an element to your current elements state array.

  const addElement = () => {
    const elementsSlice = elements.slice();
    const newElement = (
      <Example
        position={elements.length}
        deleteHandler={handleElementDelete}
        key={elements.length}
      />
    );
    elementsSlice.push(newElement);
    setElements(elementsSlice);
  };
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