【问题标题】:React Reducer function to return array of objectsReact Reducer 函数返回对象数组
【发布时间】:2016-12-16 14:58:29
【问题描述】:

如果我有一个代表购物车的对象数组(在 React 中)

[ { id: 1, qty: 1 } ]

向state 添加项目的一种巧妙方法是什么?

我需要检查数组是否包含具有该 id 的对象,如果包含则更新其数量,如果不包含则只需创建一个新数组元素添加此新对象。

我试图用新的 ES6 语法以函数式风格编写它,这让我自己陷入了混乱……这就是我目前所拥有的……

let initialState = []

  export default function shoppingCart(state=initialState, action) {
    switch(action.type) {
        case 'ADD_TO_CART':
            // check the array of objects and only act on the one we are interested in 
            let newQty = action.payload.qty
            console.log("state : ", state)
            for(let i = 0; i < state.length; i++) {
               if (state[i].id === action.payload.id) {
                   newQty = state[i].qty + action.payload.qty
                   console.log("QTY : " + newQty)
               }
           }
           //Obviously this will not work if the {id ...} already exists
           return [ ... state, {id:action.payload.id, qty:newQty} ] // todo: update this to contain the payload with qty included

       case 'REMOVE_FROM_CART':
           return state.filter(elem => elem.id !== action.payload.id)
       default:
           return state
   }
}

【问题讨论】:

    标签: reactjs reducers ecmascript-2016


    【解决方案1】:

    您可以使用Array.prototype.splice 将数组项替换为另一个:

    case 'ADD_TO_CART':
      const index = state.findIndex(item => item.id === action.payload.id)
      if (index > -1) {
        state.splice(index, 1, {
          id: action.payload.id,
          qty: state[index].qty + action.payload.qty
        })
        return [...state]
      }
      else {
        return [...state, {
          id: action.payload.id,
          qty: newQty
        }]
      }
    

    【讨论】:

    • 范式是数组是不可变的
    • 我想我可以先切片()
    • 那里是不可变的。 [...state] 是一个新数组。
    • 就是这样。说得通。谢了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2018-01-25
    • 2020-09-02
    • 2020-07-20
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多