Redux购物车示例

fan*_*dro 0 reactjs redux

我'试图了解一个名为"购物车"给予了终极版为例: https://github.com/reactjs/redux/tree/master/examples/shopping-cart

在这个例子中,你可以添加元素到你的项目列表,我试图实现删除项目列表的功能:

但是在reducers文件夹中有一个addedIds()函数,我添加了一个案例来删除列表的元素,但我不知道如何实现它,这里是函数:我的代码的reste工作正常我只是不知道如何从addedIds数组中删除产品ID.

const initialState = {
  addedIds: [],
  quantityById: {}
};

function addedIds(state = initialState.addedIds, action) {
  switch (action.type) {
    case ADD_TO_CART:
        console.log("added ADD");
      if (state.indexOf(action.productId) !== -1) {
        return state
      }
      return [ ...state, action.productId ];
    case REMOVE_TO_CART:
        console.log("removed ADD");
        // here is my problem
    default:
      return state
  }
}
Run Code Online (Sandbox Code Playgroud)

我假设我需要做类似这样的事情: 这是使用redux删除项目的正确方法吗?

但我不知道怎么做

你能帮我吗 ?

jus*_*ris 7

您可以从数组中删除一些元素,只是将其过滤掉:

// ... skipped other cases from the switch
case REMOVE_TO_CART:
    return state.filter(productId => action.productId !=== productId)
Run Code Online (Sandbox Code Playgroud)

使用.filter()函数的方法看起来很短,并根据需要生成一个新的数组实例redux.