如何使用 Redux Toolkit 應用多個過濾器
P粉600845163
P粉600845163 2024-02-21 17:03:42
0
1
456

我正在嘗試按類別過濾數據,例如使用 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 設定為完整的項目列表,然後單獨套用每個過濾器。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板