【问题标题】:Update a value in the object in an Array in react in Redux在 Redux 的反应中更新数组中对象中的值
【发布时间】:2020-08-18 16:39:28
【问题描述】:

我正在调度一个将更新 redux 状态中的值的操作,并且我正在传递一个数组。但在此之前,我想通过更改对象值来更新数组,但我不断收到错误 - 无法分配给对象的只读属性“位置”

我不确定为什么会收到此错误,因为我正在创建一个新数组并更新其中的值。

代码

export const GetCustomers= (customers) => (dispatch, getState) => {
  let activeCustomers = Array.from(customers);
  for (let i = 0; i < activeCustomers.length; i += 1) {
     activeCustomers[i].position = i;
  }

  dispatch(actions.updateActiveCustomers(activeCustomers));
  );
};

出现错误 - 无法分配给对象的只读属性“位置”

我不确定为什么会收到此错误,因为我正在创建一个新数组并更新其中的值。

【问题讨论】:

  • Array.from 只做浅拷贝,所以activeCustomers[i]customers[i] 一样
  • 当您在 Array.from .. 之后记录 activeCustomers 时会发生什么?
  • @RobinZigmond 如何将其设为 deepCopy?

标签: javascript reactjs react-redux react-state-management


【解决方案1】:

要深拷贝使用:

  let activeCustomers = JSON.parse(JSON.stringify(customers));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2019-08-12
    相关资源
    最近更新 更多