【问题标题】:Updating an object's deep property with Redux reducers使用 Redux reducers 更新对象的 deep 属性
【发布时间】:2017-04-14 19:51:41
【问题描述】:

我有以下结构。我有一个 Company 对象,它在一个数组中包含许多 Person 对象。

companies: CompanyInterface = {
   persons: PersonInterface[] = []
}

我正在尝试在表格中显示属于该公司的人员。但是,当我将人员添加/删除到人员数组时,它应该会自动更新。

现在我的减速器是这样的:

// Initial state
companies: CompanyInterface[];

// Reducer
case Constants.GLOBAL_COMPANY_ADD_PERSON:
  [action.payload.person].concat(state.companies.filter(company => company.id === action.payload.id)[0].persons));

  return {
    ...state
  };

虽然我可以验证 concat 是否正常工作(我可以在控制台登录时看到 [Person]),但它不会更新商店中的任何内容。

那么在 Redux 中更新数组(父对象中的属性)最好的方法是什么?

谢谢。

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    您可能想看看Array.prototype.concat,因为它不会对数组进行原地变异,而是returns a new array。在您的示例中,您没有改变状态。

    相反,您需要用新值替换旧值。例如:

    case 'ADD_ELEMENT':
       const { elements: previousElements } = state;
       const newElement = action.payload;
       const newElements = previousElements.concat(newElement)
       return {
          ...state,
          elements: newElements
       };
    

    【讨论】:

    • 当我改变它时,React 抱怨在 reducer 中改变数据。你能详细说明一下吗?另外,你从哪里得到 newElement ?它不是公司对象。 action.payload 是一个应该被推送到公司属性中的对象。
    • 这个例子是为了说明模式应该是什么,见redux.js.org/docs/introduction/CoreConcepts.html你的这段代码显然什么也没做。您只是将新人连接到以前的人,而不将返回值存储在任何变量中,然后返回以前的状态。正如@momentator 向您解释的那样,您需要将该值存储在一个变量中,然后返回一个带有companies 更新的新状态。
    • 我也试过 Momenator 的例子。我收到 JS 错误,上面写着“Reducer 内部检测到了一个被禁止的突变。”。其实我有点困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2018-07-01
    • 1970-01-01
    • 2016-09-13
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多