【问题标题】:Using immer can not modify property Number of nested object使用 immer 不能修改属性 Number of nested object
【发布时间】:2021-02-19 20:57:05
【问题描述】:

我正在使用带有 Redux 的 Angular 2+ 并且很好, 但不能用新值修改数量

错误是: TypeError:无法分配给对象“[object Object]”的只读属性“数量”

export interface CartState {
    readonly cars: CartCarModel[]
  }

  export class CartCarModel {
    constructor (
      public carId: string,
      public carModel: string,
      public quantity: number,
      public price: number) { }
  }


  const initialState: CartState = {
    cars: []
  }

  function reducerFunc (state: CartState, id: string, quantity: number) {
    const nextState = produce(state, draft => {
    draft.cars.find(d => d.carId === id).quantity = quantity
  })

  return Object.assign({}, state, {
    drinks: nextState
  })
}

【问题讨论】:

    标签: javascript object redux immer.js redux-reducers


    【解决方案1】:

    因为在 redux 中你不能修改 state 的值 你必须复制值 所以使用map 而不是find 我希望一切顺利

    【讨论】:

    • 同样的错误 TypeError: Cannot assign to read only property 'quantity' of object '[object Object]' ``` function reducerFunc(state: CartState, id: string, quantity: number) { const nextState = product(state, draft => { draft.cars.map( ops => { if (ops.carId === id) { return ops.quantity = quantity; } else { return ops} }) }) 返回对象.assign({}, state, { car​​s: nextState }) }```
    • 因为你仍然在编辑同一个引用,你必须克隆对象并像那样返回 ``` if(ops.carld===id) return {...ops,quantity:quantity}否则返回操作```
    • 我只是测试它但没有工作,没有错误并且数量相同 if (ops.drinkId === id) { return {...ops, quantity: quantity} } 我正在调试用chrome和数量是一样的
    • 我已经检查了你的实现,所以我发现你设置了只读汽车:CartCarModel[] 尝试删除只读关键字
    • blog.ng-book.com/… 看看这个...没有只读关键字
    猜你喜欢
    • 2022-12-06
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2021-10-25
    • 2022-01-21
    相关资源
    最近更新 更多