【问题标题】:Filter duplicate category after map in react在反应中过滤地图后的重复类别
【发布时间】:2020-07-29 20:49:03
【问题描述】:

在我的类别的动态显示(获取对象)之后.. 我只想删除重复项,但在 map () 中我不明白如何执行此操作...

问题是 map 在单个数组中返回每个类别

我应该在 jsx 中还是在函数 js 中这样做?

谢谢大家

const SideMenu = () => {
  const [loading, products] = useFetchAllProducts();
  console.log("products", products);

  const loadCategory = (i) => {
    console.log(i);
    return i;
  };

  const filterCategory = (c) => {
    return c;
  };

  return (
    <div>
      <ul>
        {products.map((link, index) => (
          <li key={link._id} onClick={() => loadCategory(index)}>
            {filterCategory(link.categoryProduct)}{" "}
          </li>
        ))}

        {/* Result =
              Masks
              Teddy
              Teddy
              Backpack
              Pencil case
              Pencil case
              Pencil case 
              ...
       */}
      </ul>
    </div>
  );
};

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    使用a Set 将产品缩减为独特的类别:

    const SideMenu = () => {
      const [loading, products] = useFetchAllProducts();
    
      // Make a set of unique categories...
      const categorySet = new Set(products.map((p) => p.categoryProduct));
      // ... and a sorted array from the set.
      const categories = Array.from(categorySet).sort();
    
      return (
        <div>
          <ul>
            {categories.map((category, index) => (
              <li key={category}>{category}</li>
            ))}
          </ul>
        </div>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 2021-03-17
      • 2021-03-30
      • 2013-10-19
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2019-12-13
      • 2020-01-14
      相关资源
      最近更新 更多