[英]category filter data by user select, category price color and brand
如何通過側邊欄選擇過濾數據? 例子:
用戶 select 一個類別,示例(電話)然后顯示具有電話類別的產品。
用戶 select 一種顏色,例如(藍色)然后顯示具有藍色的產品。
用戶 select 一個品牌,例如(蘋果)然后顯示具有蘋果品牌的產品。
用戶 select 一個價格,<= $900 然后顯示產品的價格低於或高於該價格。
用戶可以 select 所有這些一起或只是特定的 select,
稍后,也許我們可以添加更多像大小這樣的部分..!
*我的API有所有這些細節,比如類別顏色價格......
*我使用 redux 工具包做出反應!
[圖像示例][1] [1]:https://i.stack.imgur.com/FeAeW.png
我的代碼,redux 過濾片。
const initialState = {
products: [],
};
export const filterSlice = createSlice({
name: "filters",
initialState,
reducers: {
addProducts: (state, action) => {
const product = action.payload
state.products = product
},
selectedCategory: (state, action) => {
const filter = state.products.filter(product => product.categories.includes(action.payload))
state.products = filter
},
selectedColor:(state, action) => {
const filter = state.products.filter(product => product.color.includes(action.payload))
state.products = filter
},
selectedBrand:(state, action) => {
const filter = state.products.filter(product => product.brand.includes(action.payload))
state.products = filter
}
}
});
反應
const handleCategories = (tag) => {
dispatch(selectedCategory(tag));
};
const handleColor = (color) => {
dispatch(selectedColor(color));
};
const handleBrand = (brand) => {
dispatch(selectedBrand(brand));
};
您不顯示代碼。 但這是一種方法。
如果您的 API 返回帶有這些參數的 object,可以說:
price: 300
color: "red",
brand: "samsung",
itemIs: "phone"
你可以這樣做:
function onSearchQueryChange(e) { const usersSearchValue = e.target.value //comes from onChange HTMLEvent const allProducts = fetchAllProductResultsFromApi() //you will define this as an array of all the products const filteredProducts = allProducts.filter((product) => product.price.contains(usersSearchValue) || product.color.contains(usersSearchValue) || product.brand.contains(usersSearchValue) || product.itemIs.contains(usersSearchValue)) setUseStateProducts(filteredProducts) // you will map this in jsx return //something like this }
也只是告訴你,如果你采取類似的方法,你不想運行 onSearchQueryChaneg 函數,因為它每次用戶輸入 1 char 時都會調用你的 fetch 因為它調用了太多的 fetch req 所以當按下 enter 或有時調用它油門輸入。
如果可以的話,這里還有一個更簡單的方法:
如果您可以讓每個對象都具有某種數組屬性:
tags: ["samsung", "phone", "300", "red"]
那么這將使它變得更容易,相反,您可以將filteredProducts更改為:
const filteredProducts = allProducts.filter((product) => product.tags.includes(usersSearchValue)); //even simpler!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.