简体   繁体   中英

Redux: Does this count as mutating state?

Using Redux within Angular2 (NgRedux) for updating/setting an order entry. Is it ok to mutate a proxy variable, then object.assign it to state?

In my data reducer:

case DataActions.UPDATE_ORDER:
  var updatedItem
  var updatedState = state.orders
  for(var i = 0; i < state.orders.length; ++i) {
    if(state.orders[i]['key'] === action.payload.key) {
      updatedItem = state.orders[i]
      updatedItem.name = action.payload.name
      updatedItem.items = action.payload.items
    }
  }
  updatedState[i] = updatedItem
  return Object.assign({}, state, {
    orders: updatedState
  })

Your "proxy variable" is just another reference to the same object, so yes, you are directly mutating the items in that array.

In order to correctly do immutable updates, each level of nesting should be copied. The Redux docs give examples of both common mistakes, and how to do this correctly, in Immutable Update Patterns .

Many thanks to @markerikson for the solution.

I went with the documentation's advice and used the dotProp library. This worked:

npm install dot-prop-immutable
...
var dotProp = require('dot-prop-immutable');
...
case DataActions.UPDATE_ORDER:
  for(var i = 0; i < state.orders.length; ++i) {
    if(state.orders[i]['key'] === action.payload.key) {
      state = dotProp.set(state, `orders.${i}.name`, action.payload.name)
      state = dotProp.set(state, `orders.${i}.items`, action.payload.items)
    }
  }
  return state

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