Estoy tratando de eliminar un elemento de un childArray que está anidado en otro Array.
Así es como lo estoy intentando.
const childArrayHandler = (childData, sub, questionId, data, btnId) => { // Manage color change on click const isInList = selectedBtnList.some((item) => item === btnId) if (isInList) { onSelectedBtnListChange(selectedBtnList.filter((item) => item !== btnId)) } else { onSelectedBtnListChange([...selectedBtnList, btnId]) } // Manage childData Array // copy data to mutable object const currentChildData = [...childData] const hasId = currentChildData.find(({ id }) => sub.id === id) if (!hasId) { // add item to childArray if same index is not available in the childArray const newChild = { id: sub.id, sub_question: sub.sub_question, weightage: sub.weightage } currentChildData.push(newChild) setChildDataOnChange((current) => [...current, newChild]) } else if (hasId) { // remove item from childArray if same index is available in the childArray const indexOfChild = currentChildData.indexOf(hasId) // console.log('currentChildData', currentChildData, 'indexOfChild', indexOfChild) currentChildData.slice(indexOfChild, 1) setChildDataOnChange(currentChildData) } const newData = [...data] // find parent of the child const parent = newData.find(({ parentId }) => questionId === parentId) // find index of parent const indexOfParent = newData.indexOf(parent) // update data with child related to parent newData[indexOfParent].child = currentChildData onDataChange(newData) localStorage.setItem('deviceReport', JSON.stringify(newData)) } El problema está en el bloque else if , quiero que si hay un índice de objeto disponible en el elemento secundario, entonces debería eliminarlo de la matriz. Por lo que puedo ver, estoy usando el enfoque correcto como se sugiere en otros artículos, pero me falta algo que no puedo ver en este momento. Pero no es capaz de encontrar el resultado adecuado. Si me consuelo no cambia nada. significa no eliminar ningún elemento de la matriz si el índice ya está allí.
Entonces, ¿cómo puedo solucionar esto, o qué podría estar haciendo mal? ¿Hay alguna otra forma de hacerlo? Por favor, menciónelo también. Gracias
Tienes el problema con esta rebanada
currentChildData.slice(indexOfChild, 1)No inicializa una nueva matriz para usted ( inmutabilidad de React )
La solución podría ser
currentChildData = currentChildData.slice(0, indexOfChild).concat(currentChildData.slice(indexOfChild + 1)) Si cree que es demasiado complicado, puede usar el filter en su lugar
currentChildData = currentChildData.filter((item) => item !== hasId) //`hasId` is your found item with `find`El segundo problema aquí es
newData[indexOfParent].child = currentChildDataNo puede asignar un valor a un objeto mutado
La forma correcta debe ser
newData = newData.map((item) => item === parent ? {...item, child: currentChildData} : item)El código completo
const childArrayHandler = (childData, sub, questionId, data, btnId) => { // Manage color change on click const isInList = selectedBtnList.some((item) => item === btnId) if (isInList) { onSelectedBtnListChange(selectedBtnList.filter((item) => item !== btnId)) } else { onSelectedBtnListChange([...selectedBtnList, btnId]) } // Manage childData Array // copy data to mutable object let currentChildData = [...childData] const hasId = currentChildData.find(({ id }) => sub.id === id) if (!hasId) { // add item to childArray if same index is not available in the childArray const newChild = { id: sub.id, sub_question: sub.sub_question, weightage: sub.weightage } currentChildData.push(newChild) setChildDataOnChange((current) => [...current, newChild]) } else { // console.log('currentChildData', currentChildData, 'indexOfChild', indexOfChild) currentChildData = currentChildData.filter((item) => item !== hasId) setChildDataOnChange(currentChildData) } //let newData = [...data] // find parent of the child //const parent = newData.find(({ parentId }) => questionId === parentId) // update data with child related to parent //newData = newData.map((item) => item === parent ? {...item, child: currentChildData} : item) //shorter version const newData = data.map((item) => item.parentId === questionId ? {...item, child: currentChildData} : item) onDataChange(newData) localStorage.setItem('deviceReport', JSON.stringify(newData)) }