繁体   English   中英

按用户 select 分类过滤数据,分类价格颜色和品牌

[英]category filter data by user select, category price color and brand

如何通过侧边栏选择过滤数据? 例子:

  1. 用户 select 一个类别,示例(电话)然后显示具有电话类别的产品。

  2. 用户 select 一种颜色,例如(蓝色)然后显示具有蓝色的产品。

  3. 用户 select 一个品牌,例如(苹果)然后显示具有苹果品牌的产品。

  4. 用户 select 一个价格,<= $900 然后显示产品的价格低于或高于该价格。

  5. 用户可以 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM