简体   繁体   中英

How to update certain key values in an object nested in the redux state

I have the following data:

Project : {id:10,
           requirements: [{id:1,
                           title:test},
                          {id:2,
                            title:test2}]
          }

and

action.payload : {id:1,
                  title:changed_title}

What i wish to update the requirement object of id:1 within my redux reducer.

Heres what i have so far but it doesn't seem to be working and its super messy:

  case 'requirements_update': return (updateObject(state, project: {...state.project , requirements: state.project.requirements.filter(requirement => 
                                                                                                                                            {if(requirement.requirement_id === action.payload.requirement_id)
                                                                                                                                                
                                                                                                                                            return(action.payload) }
                                                                                                                                            })}))

You can use map and id check to update project

project : state.project.map(project => project.id === payload.id ? payload : project)

The double spreading at the bottom is to merge current requirement properties with action payload, (action payload properties will have priority since they will override existing ones)

case 'requirements_update':
  return {...state, state.project: {...state.project , requirements: state.project.requirements.map(requirement => {
    if (requirement.id === action.payload.id) {
      return {...requirement, ...action.payload}
    } else {
      return requirement
    }
  }}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM