如何在Redux Reducer中的对象嵌套数组中添加项目

时间:2019-08-22 16:57:24

标签: javascript reactjs redux

这是我的示例初始状态:

let initialState = {
    data: {
        name: 'john',
          books: [
              {
                  name: 'a',
                  price: 220
              }
          ]
    }
}

如何将新书添加到书中?

我已经尝试过

return {
        ...state,
        data :{
          ...state.data,
          books:{
              ...state.data.books,
              name : state.data.books.concat(action.payload.item.name),
              price : state.data.books.concat(action.payload.item.price)
          }
      }
      };

有什么想法吗?

重要提示:我不想删除书本中已有的要添加动作有效载荷的新书

4 个答案:

答案 0 :(得分:3)

您错过了一些括号,特别是books是数组,并且您要插入新对象

return {
        ...state,
        data: {
          ...state.data,
          books: [
              ...state.data.books,
              {
                  name: action.payload.item.name,
                  price: action.payload.item.price
              }
          ]
      }
};

答案 1 :(得分:0)

首先,books是数组。其次,如果您只想向数组添加新项,则可以使用数组传播运算符。

books: state.data.books.concat(action.payload.item)也可以。

return {
  ...state,
  data: {
    ...state.data,
    books: [
      ...state.data.books,
      action.payload.item
    ]
  }
};

答案 2 :(得分:0)

让我们通过发明便捷工具使我们的工作更轻松-

const update = (key, { [key]: value, ...state }, f) =>
  ({ ...state, [key]: f (value) })

const initState =
  { data:
      { name: "john"
      , books: [ { name: "a", price: 20 } ]
      }
  }

const payload =
  { item: { name: "b", price: 30 } }

const nextState =
  update ('data', initState, x =>
    update ('books', x, arr =>
      [ ...arr, payload.item ]
    )
  )

console.log(initState)
console.log(nextState)

输出

// initState
{ data:
    { name: "john"
    , books:
        [ { name: "a", price: 20 } ]
    }
}

// nextState
{ data:
    { name: "john"
    , books:
        [ { name: "a", price: 20 }
        , { name: "b", price: 30 }
        ]
    }
}

答案 3 :(得分:0)

答案很简单

const book = {
            name : action.payload.item.name,
            price : action.payload.item.price
           };
return {
    ...state,
    data :{
      ...state.data,
      books: state.data.books.concat(book)              
      }      
};

您可以在这里找到不变的更新模式

Redux updated patterns