首页 > 解决方案 > React - 从数组中过滤一些对象

问题描述

我想从数组中过滤一些对象,但目前我只知道删除单个对象,这是我当前的代码看起来像

const deleteChatList = (dispatch) => async (id) => {
    dispatch({type: 'delete', payload: id}) // need to change id to list of id or list of object
}

...

const chatListReducer = (state, action) => {
    switch (action.type) {
        case 'fetch':
            return {...state, chatList: action.payload}
        case 'delete':
            return state.filter((chatList) => chatList.id !== action.payload)
        default:
            return state;
    }
}

任何人都可以帮助我吗?

标签: arraysreactjsreact-nativearray-filter

解决方案


您可以使用Set进行成员资格检查。对象也可能起作用。

const deleteChatList = (dispatch) => async (chatListDeleted) => {
    dispatch({type: 'delete', payload: [id1, id2, id3]}) 
}
...

const chatListReducer = (state, action) => {
    switch (action.type) {
        case 'fetch':
            return {...state, chatList: action.payload}
        case 'delete':
            const idSet = new Set(action.ids)
            return state.filter((chatList) => idSet.has(chartList.id))
        default:
            return state;
    }
}


推荐阅读