Estoy tratando de establecer un nuevo estado, pero lo único que cambia es un elemento en esta matriz. Todavía soy muy nuevo en javascript, así que realmente no entiendo cómo hacer la sintaxis.
Sé que puedo crear un nuevo objeto usando el operador de propagación y puedo agregar/cambiar algo en el objeto si está en el nivel superior, pero ¿cómo lo hago en una matriz?
newRow = { name: "kevin" status: false } currentStageData = { name: "Stage 1" items: [ { name: "david" status: true }, { name: "kevin" status: true }, { name: "bruce" status: true }, ] }Intenté hacer esto pero esta sintaxis no funciona.
var newCurrentStageData = { ...currentStageData, newCurrentStageData.items[index]: newRow }Así que termino teniendo que hacer esto.
var newRow = { ...row, status: e.target.checked } var newCurrentStageData = { ...currentStageData } newCurrentStageData.items[index] = newRowLa difusión no funcionará aquí porque el índice en el que desea insertar el elemento no está necesariamente al final o al principio.
Su enfoque actual también viola las reglas de React al mutar el estado, lo que nunca debe hacerse.
Si el índice ya está presente en la matriz, .map para crear uno nuevo, reemplazando el elemento en el mismo índice cuando se cumpla la condición.
const newCurrentStageData = { ...currentStageData, items: currentStageData.items.map((item, i) => i === index ? newRow : item) };Pero realmente no lo pondría todo en una sola línea. La legibilidad es más importante que la compresión de línea.
const newCurrentStageData = { ...currentStageData, items: currentStageData.items.map( (item, i) => i === index ? newRow : item ) };