El componente no se vuelve a representar después de la eliminación de un elemento en el estado, pero el estado cambia. En el componente, puede agregar un elemento en la matriz (que es un estado) a través del formulario, ver todos los elementos en la matriz y eliminarlo del estado usando el botón. Entonces, después de eliminar un elemento que está en el estado, el componente no se vuelve a representar. El siguiente es el código del componente:
import React, { useEffect, useState } from 'react'; import { Typography, IconButton, Button, TextField, Paper, } from '@mui/material'; import { CancelOutlined, AddBoxOutlined, VisibilityOutlined, VisibilityOffOutlined, } from '@mui/icons-material'; export default function Test1() { const [subNames, setSubNames] = useState([]); const [subName, setSubName] = useState(''); const [showSubForm, setShowSubForm] = useState(false); const onSubNameChange = (e) => { setSubName(e.target.value); }; const onSubNameSubmit = () => { if (!subName) return alert('Enter name!'); setSubNames((prev) => prev.concat({ name: subName })); setShowSubForm(false); setSubName(''); }; const subForm = ( <> <div sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', }}> <TextField label='Sub Todo Name' onChange={onSubNameChange} name='subTodoName' value={subName} size='small' variant='outlined' fullWidth /> <IconButton onClick={onSubNameSubmit}> <AddBoxOutlined color='primary' /> </IconButton> </div> <br /> </> ); const onDelete = (position, e) => { let arr = subNames; arr.splice(position, 1); setSubNames(arr); }; return ( <div> <h1>Hello World!</h1> {subNames.map((item, key) => ( <Paper key={key} sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: 'auto', padding: 10, marginTop: 10, borderRadius: '10px', }} elevation={3}> <div sx={{ display: 'flex', alignItems: 'center' }}> <Typography variant='body1'> <b>Sub Todo-{key + 1}:</b> </Typography> <Typography variant='body1'>{item?.name}</Typography> </div> <IconButton onClick={(e) => onDelete(key, e)}> <CancelOutlined color='primary' /> </IconButton> </Paper> ))} <br /> {showSubForm && subForm} <div> {showSubForm && ( <Button variant='contained' sx={{ float: 'right' }} color='primary' size='small' startIcon={<VisibilityOffOutlined />} onClick={() => setShowSubForm(false)}> Add sub todo item </Button> )} {!showSubForm && ( <Button variant='contained' sx={{ float: 'right' }} onClick={() => setShowSubForm(true)} color='primary' size='small' startIcon={<VisibilityOutlined />}> Add sub todo item </Button> )} </div> </div> ); }React no se volverá a renderizar, porque es como si nada hubiera cambiado, es decir, cada vez que le das el mismo state a un setState . Para tipos primitivos como String , Boolean ... es obvio saber si estamos dando valores diferentes o no. Para tipos de referencia como Array , Object ... por otro lado, cambiar su contenido no los marca como un valor diferente para React. Debería ser una referencia diferente.
Mientras lo hace, está dando la misma referencia de memoria a setSubNames .
let arr = subNames; // will do just a reference copy -> arr==subNamesUna solución podría ser el operador de propagación, creará una copia de su matriz existente pero en una nueva referencia de memoria, así:
const onDelete = (position, e) => { let arr = subNames; arr.splice(position, 1); setSubNames([...arr]); };