简体   繁体   中英

A better way to update state in redux reducer

Please advise me what is better way. Both ways return same result.

payload = { value1: 'test1', value2: 'test2' }

Example1:

case EXAMPLE_TYPE:
  return {
    ...state,
    ...action.payload
  };

Example2:

case EXAMPLE_TYPE:
  return {
    ...state,
    value1: action.payload.value1,
    value2: action.payload.value2
  };

Your both examples are ok.

Depending on what you need, you can use them both.

Personally I prefer to destructure the payload first, and then insert them into the new state object like so.

const { value1, value2 } = action.payload
return {
   ...state,
   value1,
   value2,
}

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