简体   繁体   English

Redux:这算作变异状态吗?

[英]Redux: Does this count as mutating state?

Using Redux within Angular2 (NgRedux) for updating/setting an order entry. 在Angular2(NgRedux)中使用Redux更新/设置订单条目。 Is it ok to mutate a proxy variable, then object.assign it to state? 可以先更改代理变量,然后对object.assign进行声明,这样行吗?

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 . Redux文档在不可变更新模式中提供了两个常见错误以及如何正确执行此操作的示例。

Many thanks to @markerikson for the solution. 非常感谢@markerikson提供的解决方案。

I went with the documentation's advice and used the dotProp library. 我接受了文档的建议,并使用了dotProp库。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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