搜尋

首頁  >  問答  >  主體

如何使用 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粉600845163265 天前408

全部回覆(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
  • 取消回覆