如何使用 Redux Toolkit 应用多个过滤器
P粉600845163
P粉600845163 2024-02-21 17:03:42
0
1
450

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

全部回复(1)
P粉978742405

我可能会做类似的事情

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板