搜索

首页  >  问答  >  正文

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

我正在尝试按类别过滤数据,例如使用 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
            )
        },
    }
})

我尝试在一个减速器中编写过滤器,但它仍然不起作用

P粉600845163P粉600845163319 天前476

全部回复(1)我来回复

  • P粉978742405

    P粉9787424052024-02-22 10:06:57

    我可能会做类似的事情

    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 设置为完整的项目列表,然后单独应用每个过滤器。

    回复
    0
  • 取消回复