简体   繁体   中英

How can I update only part of the state

Here is the State object:

const initialState = {
  data: {
    user: '',
    token: '',
  }
}

Reducer:

case 'DO_SOMETHING':
return {...state, data: action.payload }

If I soft copy the state as shown above, I will overwrite the entire data part of the state. How can I update only the user with the given payload without overwriting the token ?

If the payload is just the user , then simply use the same destructuring pattern you used for the state object in general:

return {
  ...state,
  data: {
    ...state.data,
    user: action.payload
  }
}

This pattern can be nested as much as you like, so you can have large structured state objects and just pass around the fields you want in the payloads.

Try this, (considering action.payload is the entire data object)

case 'DO_SOMETHING':
return {...state, data: { ...state.data, user: action.payload.user } }

Spread the nested object too:

return {...state, data: {...state.data, user: action.payload} }

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