Tengo la siguiente matriz de objetos:
const [rows, setRows] = useState([ {id: 1, key: "key1", value: "value1"}, {id: 2, key: "key2", value: "value2"} ]);Y también tengo las siguientes entradas:
<TextField name="key" onChange={(e)=> handleTable(e, record.id)} value{rows.filter...}/> <TextField name="value" onChange={(e)=> handleTable(e, record.id)} value{rows.filter...}/>Ahora sé que para manejar las entradas anteriores, debo hacer un bucle para encontrar el objeto apropiado en función de su ID y luego intentar actualizarlo, necesito otro bucle para el valor de las entradas anteriores también, pero eso lleva mucho tiempo. términos de enganches y recarga cada vez que el usuario ingresa algo, ¿cómo puedo manejar la situación anterior, actualizando y mostrando el elemento apropiado en la matriz?
Sí, debe recorrer los campos de texto y pasar el índice al controlador de cambios.
const [rows, setRows] = React.useState([ { id: 1, key: "key1", value: "value1" }, { id: 2, key: "key2", value: "value2" } ]); const handleChange = (e,idx) => { clone = [...rows]; let obj = clone[idx]; obj.value = e.target.value; clone[idx] = obj; setRows([...clone]) }y luego necesita hacer un bucle en sus filas con el campo de texto.
{ rows?.map((row, index) => <TextField value={rows[index]?.value} onChange={(e) => handleChange(e,index)} /> )}Esto puede ayudarlo a modificar su solución.
const [rows, setRows] = useState([ { id: 1, key: "key1", value: "value1" }, { id: 2, key: "key2", value: "value2" } ]); const handleTable = (e, id) => { const newRows = [...rows]; //spread the rows array into a new array const index = rows.find((item, i) => { if (item.id === id) return i; }); //found the index using the id if (e.target.name === "key") { newRows[index].key = e.target.value; // update using the index } else { newRows[index].value = e.target.value; } setRows(() => [...newRows]); }; <TextField name="key" onChange={(e)=> handleTable(e, record.id)} value{rows.filter...}/> <TextField name="value" onChange={(e)=> handleTable(e, record.id)} value{rows.filter...}/>si hay una mejor manera, por favor edite
const [value , setValue]=useState([])en html:
*necesita un estado separado para cada elemento de entrada
<input value={value[key] ? value[key] : ""} onChange={(e) => handleSetValue(e.target.value, key)}/>establecer valor func() :
function handleSetValue(e, key) { setValue(s => { const newArr = s.slice(); newArr[key] = e; return newArr; }); }