繁体   English   中英

我如何清除处于redux状态的数组以进行多选

[英]How do i clear array in redux state for a multi select

提前致谢。 如果用户单击清除按钮,则需要清除我的redux状态数组。 当它们击中每张图像时,该项目将添加到redux状态数组,并且所选项目会在UI中获得边框。 我有一个清除按钮,可以清除用户选择。 我该如何执行呢?

我的动作和减速器如下:

行动

export const selectedItem = (selectedItem ) => {
    return {
        type: 'selected_Item',
        payload:selectedItem 
    }
}

减速器

import _, { map, isEmpty } from 'lodash'

const INITIAL_STATE = {
    itemList: []
}

export default (state = INITIAL_STATE, action) => { 
    console.log('REDUX__ '+action.payload)
    switch (action.type) {
        case 'selected_Item':

        var idx = _.findIndex(state.itemList, function(o) { return o.ITEMID== action.payload.ITEMID; }); 
        if(idx!==-1){
            state.itemList.splice(idx, 1) 
            return { ...state, itemList: [...state.itemList] }
        }       
            return { ...state, itemList: [...state.itemList, action.payload] }


        default:
            return state;
    }
}

我是否必须维护单独的reducer和操作以清除此状态数组? 我怎样才能做到这一点。 我更喜欢将代码支持作为对本机和redux的新响应。

再次感谢您的检查。

只需添加一个删除案例:

case 'delete_items':
  return { ...state, itemList: [] }

甚至像这样,如果可能的话:

case 'delete_items':
  return { ...INITIAL_STATE }

试试下面的代码。

动作:

 export const selectedItem = (selectedItem) => { return { type: 'selected_Item', payload:selectedItem } } export const clearItems = () => { return { type: 'clear_Items' } } 

减速器:

 import _, { map, isEmpty } from 'lodash' const INITIAL_STATE = { itemList: [] } export default (state = INITIAL_STATE, action) => { console.log('REDUX__ '+action.payload) switch (action.type) { case 'selected_Item': var idx = _.findIndex(state.itemList, function(o) { return o.ITEMID== action.payload.ITEMID; }); if(idx!==-1){ state.itemList.splice(idx, 1) return { ...state, itemList: [...state.itemList] } } return { ...state, itemList: [...state.itemList, action.payload] } case 'clear_Items': return { ...state, itemList: [] } default: return state; } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM