Quiero actualizar el estado de reacción usando redux pero los datos no se ordenan correctamente
matriz original
"sections": [ { "id": 8, "user_id": 1, "field_type_id": 8, "section_id": 3, "value": "+96******", "type": "phone", "url": "tel:", "icon": "phone" } { "id": 9, "user_id": 1, "field_type_id": 8, "section_id": 3, "value": "test@gmail.com", "type": "email", "url": "", "icon": "email" } ]Estoy actualizando el estado usando este código.
state = { ...state,sections :[ ...state.sections.filter( (section) => section.id !== action.payload.section.id ) , action.payload.section ] } return stateDespués de actualizar, los objetos de la matriz se invierten
"sections": [ { "id": 9, "user_id": 1, "field_type_id": 8, "section_id": 3, "value": "test@gmail.com", "type": "email", "url": "", "icon": "email" } { "id": 8, "user_id": 1, "field_type_id": 8, "section_id": 3, "value": "+91344******", "type": "phone", "url": "tel:", "icon": "phone" } ]¿Cómo puedo detener la inversión de la matriz?
Si simplemente desea actualizar un elemento en un índice específico, simplemente use Array.prototype.map para asignar la matriz anterior a la siguiente, actualizando el elemento específico cuando se alcance. Se mantiene el orden de la matriz.
const nextState = { ...state, sections: state.sections.map( section => section.id === action.payload.section.id ? action.payload.section : section ), }; return nextState;Puedes usar uno de 2:
// filter const state = { ...state, sections: state.sections.filter( (section) => section.id !== action.payload.section.id ), }; // Update const state = { ...state, sections: state.sections.map((section) => section.id !== action.payload.section.id ? { ...section, url: 'new Value' } : section ), };