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

124
Visualizações
ReactJS not rendering correct items after splice

So I am attempting to delete an item from an array in React, but after deleting (using splice) item 2 from [1, 2, 3, 4] it re-renders the array to be [1, 2, 3] (at least visually) but when I render one more time (by closing the array and opening it) it renders properly as [1, 3, 4]. Not sure why it's doing this and I think it has to do with splice() but nothing else seems to be working. I tried slice() as well but that didnt work either. Here is the code for my delete function:

const deleteFile = (i) => {
        console.log(files);
        const newFiles = [...files];
        console.log('before delete:', newFiles); //prints [1, 2, 3, 4]
        newFiles.splice(i, 1);
        console.log('after delete:', newFiles); //prints [1, 3, 4] but shows visually as [1, 2, 3]
        setFiles(newFiles);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This may be one potential way to achieve the desired objective (ie, remove the element at index i in an array named files:

const [files, setFiles] = useState([]);
const deleteFile = i => setFiles(prev => prev.filter((f, idx) => idx !== i));

NOTE: Please add index-check (i should be >= 0 and < files.length) if needed.

Explanation

  • setFiles may be used with a callback (click here for more info)
  • prev is the existing array files
  • use .filter with idx to filter out the element at index i

Code Snippet

const arr = [1, 2, 3, 4];

const deleteItemAt = i => arr.filter((el, idx) => idx !== i);

console.log(deleteItemAt(1));
console.log(deleteItemAt(0));
console.log(deleteItemAt(3));

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