【问题标题】:Immutable.JS replacing last item in array instead of appendingImmutable.JS 替换数组中的最后一项而不是追加
【发布时间】:2018-01-06 17:28:52
【问题描述】:

我在我的 redux 应用程序中使用 Immutable JS 并尝试更新我的对象中存在的数组,我只能添加一个项目,然后在每次后续添加后替换它。

/**************
INITIAL STATE
***************/
const INITIAL_STATE = Immutable.fromJS({
  budgetCategories: [
    {budgetName: 'budgetName', monthlyCost: '$200.00', rollOverEnabled: true, dueDate: 'monthly'}
  ]
});

/**************
TYPES
***************/
export const ADD_BUDGET = 'src/Budget/ADD_BUDGET';

/**************
REDUCER LOGIC FLOW
***************/
export default function (state = INITIAL_STATE, action) {
  switch (action.type) {
    case ADD_BUDGET:
      console.log("Payload is:");
      console.log(action.payload);
      return INITIAL_STATE.updateIn(['budgetCategories'], arr => arr.push(Immutable.fromJS(action.payload)))
    default:
      return state;
  }
}

示例:

状态:

Index 0:
    budgetName(pin): "rwer"
    monthlyCost(pin): "tryrtyt"
    rollOverEnabled(pin): false
    dueDate(pin): "Sat, 06 Jan 2018 17:24:44 GMT"

运行 reducer 函数并仅更改budgetName 将产生:

Index 0:
    budgetName(pin): "changedBudgetName"
    monthlyCost(pin): "tryrtyt"
    rollOverEnabled(pin): false
    dueDate(pin): "Sat, 06 Jan 2018 17:24:44 GMT"

如您所见,此代码覆盖了索引。

【问题讨论】:

  • 嘿@Rayan,试试这个: return state.updateIn(['budgetCategories'], arr => arr.push(Immutable.fromJS(action.payload))) ?
  • 是的,完美!谢谢
  • 太好了! @Rayan
  • @LefiTarik 请添加答案而不是评论。请参阅Comment everywhere 上的我什么时候不应该发表评论?部分。

标签: javascript reactjs redux react-redux immutable.js


【解决方案1】:

返回 state 而不是 INITIAL_STATE

return state.updateIn(['budgetCategories'], arr =>
  arr.push(Immutable.fromJS(action.payload))
);

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 2010-12-13
    • 1970-01-01
    • 2018-02-25
    • 2014-04-15
    • 1970-01-01
    • 2021-10-18
    • 2012-07-13
    相关资源
    最近更新 更多