根据 Reactjs 中的类别过滤列出的项目

问题描述 投票:0回答:2

我一直在努力获取按类别列出的项目数据

我不知道我做错了什么。

所以基本上,我有来自不记名令牌 API 的数据,并且它已成功在屏幕上列出,但我想作为第二步根据其类别列出。有五个类别,60多个项目。

这是我的代码:

  const [filterList, setFilterList] = useState("all");
  const [newProduct, setNewProduct] = useState(products);

  // filtering data by category

  useEffect(() => {
    let isValidScope = true;

    const fetchData = async () => {
      // pass filterList in fetch to get products for the selected category ??
      // pass parameters to fetch accordingly

      const res = await fetch(
        "https://myapi-api.herokuapp.com/api/categories/",
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (!isValidScope) {
        return;
      }

         setNewProduct(res);
    };

    fetchData();

    return () => {
      isValidScope = false;
    };
  }, [filterList]);



function onFilterValueSelected(filterValue) {
    setFilterList(filterValue);
  }
  let filteredProductList = newProduct?.filter((product) => {
    // should return true or false

    // option 2 if product has a category property
    return product.category === filterList;
    // existing code
    if (filterList === "electronics") {
      return product.electronics == true;
    } else if (filterList === "clothing") {
      return product.clothing === true;
    } else if (filterList === "accsessories") {
      return product.accsessories === true;
    } else if (filterList === "furniture") {
      return product.furniture === true;
    } else if (filterList === "hobby") {
      return product.hobby === true;
    } else {
      // here dont return truthy
      return false;
    }
  });
javascript reactjs filtering
2个回答
1
投票

您可以在组件安装时一次获取所有产品,并根据所选过滤器在每次渲染时对它们进行过滤,而不是在过滤器更改时每次在 useEffect 中获取产品。

const [filterCategory, setFilterCategory] = useState("");
   
function onFilterValueSelected(filterValue) {
    setFilterCategory(filterValue);
  }

  let filteredProductList = newProduct?.filter((product) => {
    return product.category === filterCategory;     
  });

0
投票

尝试类似的事情:

const categories = ['Cat1', 'Cat2', 'Cat3'] // Since you hardcode it anyway, its fine to have a hardcoded array here. But you can retrieve unique categories by getting Object.values on category and new Set() them
return (<> {categories.forEach(category => {
fetchedData.filter(el => el.category === category).map(filteredElement => {return <h1> {filteredElement.property} <h1>})}) </>} 

© www.soinside.com 2019 - 2024. All rights reserved.