如何从extrareducer redux中更改对象中元素的值?

ycl3bljg  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(160)

这是初始状态:

const initialState ={
  ordersWholesale:[
    {
      "id": 14,
      "name": "XTPara 650mg Tablet",
      "code": "XTP5656",
      "date": "17/10/2022",
      "accepted": null,
      "wholesale": "shakthi",
      "quantity": "5"
    },
    {
      "id": 15,
      "name": "Dolo 650 Tablet",
      "code": "DOL1213",
      "date": "17/10/2022",
      "accepted": false,
      "wholesale": "shakthi",
      "quantity": "5"
    },
  ],
}

这是切片减压器

extraReducer: {
  [asyncOrderAccept.fulfilled]: (state, { payload }) => {

  }
}

如何使用有效负载值14仅更改orderWholesale[0]['accepted']: true值?

csga3l58

csga3l581#

如果我正确理解了您的问题,即action有效负载是您希望切换为true的ordersWholesale状态元素的id,那么您需要搜索数组以查找id的正确元素,然后更新 * 那个 * 元素。ordersWholesale数组和Array.prototype.find可能返回undefined(如果未找到匹配)。

extraReducer: {
  [asyncOrderAccept.fulfilled]: (state, { payload }) => {
    const el = state.find(order => order.id === payload);
    if (el) {
      el.accepted: true,
    }
  },
}

如果您可以使用“选择性链接”,这也可能适用于您。

extraReducer: {
  [asyncOrderAccept.fulfilled]: (state, { payload }) => {
    state.find(order => order.id === payload)?.accepted = true;
  },
}

相关问题