【问题标题】:How to define a object value using a specific key when returning an object返回对象时如何使用特定键定义对象值
【发布时间】:2020-09-08 19:58:05
【问题描述】:

我需要在返回对象时更改特定键的值。我不知道有没有办法做到这一点。

很难准确说出我需要什么,但在下面的代码中很容易得到:

return {
  ...state,
  cart: [
     ...state.cart,
     state.cart[itemIndex]: {  // <- This is what I want, but this way doesn't work
       {
         productId: action.product.productId,
         quantity: action.quantity
       },
     }
  ]
}

【问题讨论】:

  • 显示您传递给减速器的操作负载以及您尝试修改的状态示例。
  • [state.cart[itemIndex]]: {

标签: javascript reactjs ecmascript-6 react-redux


【解决方案1】:

如果您尝试替换数组中的项目,则需要使用数组方法来获取正确的索引。

您可以使用Array.map() 将项目设置在请求的索引处:

return {
  ...state,
  cart: state.cart.map((item, index) => 
    index !== itemIndex ? item : {
      productId: action.product.productId,
      quantity: action.quantity
    }
  )
}

或使用Array.slice() 与数组展开:

return {
  ...state,
  cart: [
    state.cart.slice(0, itemIndex),
    {
      productId: action.product.productId,
      quantity: action.quantity
    }
    state.cart.slice(itemIndex + 1),
  ]
}

一个更短的选择是克隆数组,然后只替换请求索引中的项目:

const updatedCart = [...state.cart]
updatedCart[itemIndex] = {
  productId: action.product.productId,
  quantity: action.quantity
}

return {
  ...state,
  cart: updatedCart
}

使用immer:

import produce from 'immer'

return produce(state, draftState => {
  draftState.cart[itemIndex] = {
    productId: action.product.productId,
    quantity: action.quantity
  }
})

【讨论】:

  • 明确一点,我想要的方式不存在?
  • 较短的选项很棒,谢谢!我不知道为什么我不这么认为xD
  • 不。 Array spread just shallow 将整个数组克隆到一个新数组。您在传播后添加的所有内容都将是最后的。此外,语法 [key]: value 不适用于数组。
  • 您还应该结帐 immer - 它为您完成了不可变的繁重工作。
猜你喜欢
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多