reactjs 如何使用Redux Toolkit应用多个过滤器

5us2dqdw  于 2023-04-05  发布在  React
关注(0)|答案(1)|浏览(128)

我正在尝试使用Redux Toolkit按类别过滤数据,例如类型、品牌、颜色、性别。过滤器单独工作,但过滤器不一起工作。如果我先过滤品牌,然后过滤颜色,品牌过滤器不工作。我需要做什么才能使此工作?

const initialState = {
    products: data,
    filteredItems: data,
}

export const filterSlice = createSlice({
    name: "filter",
    initialState,
    reducers: {
        filterCategory: (state, action) => {
            if (action.payload === "All") {
                return initialState
            } else
            state.filteredItems = state.products.filter(
                (item) => item.category === action.payload
            ) 
        },
        filterGender: (state, action) => {
            state.filteredItems = state.products.filter(
                (item) => item.gender === action.payload
            ) 
        },
        filterColor: (state, action) => {
            state.filteredItems = state.products.filter(
                (item) => item.color === action.payload
            )
        },
        filterBrand: (state, action) => {
            state.filteredItems= state.products.filter(
                (item) => item.brand === action.payload
            )
        },
    }
})

我试过在一个reducer中编写过滤器,但仍然不起作用

jhkqcmku

jhkqcmku1#

我可能会做一些

const initialState = {
    products: data,
    filteredItems: data,
    filters: {}
}

reducers: {
    filterCategory: (state, action) => {
        if (action.payload === "All") {
            return initialState
        } else {
            state.filters = { ...state.filters, category: action.payload }
            state.filteredItems = state.products;
        ) 
    },
    // ...etc.
    Object.entries(state.filters).forEach(([key, value]) => {
        state.filteredItems = state.filteredItems.filter(
            (item) => item[key] === value
        );
    });
    return state;
}

以便保存哪些过滤器处于活动状态,然后将filteredItems设置为完整的项列表,然后分别应用每个过滤器。

相关问题