动态显示我的类别后。 我只想删除重复项,但是在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>
);
};
答案 0 :(得分:0)
使用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>
);
};