#javascript #reactjs
Вопрос:
Я пытаюсь отфильтровать товары по категориям,когда нажимается кнопка категории (расположена в CAtegoryFilter.js) и цвет кнопки также должен измениться. Однако никакой фильтрации не происходит, и все кнопки меняют цвет при нажатии на одну из них.
Категория продукта соответствует соответствующему идентификатору из файла category.json.
данные о продуктах и категориях приведены ниже и представляют данные, которые будут поступать из базы данных.
//categories.json
[{
"id": {
"cID": "5f15d5cdcb4a6642bddc0fe9e"
},
"name": "Electronics",
"__v": 0
},{
"id": {
"cID": "5f15d545f3a046427a1c26e2"
},
"name": "Beauty",
"__v": 0
},{
"id": {
"cID": "5f15d54cf3a046427a1c26e3"
},
"name": "Computers",
"__v": 0
},{
"id": {
"cID": "5f15d5b2cb4a6642bddc0fe7"
},
"name": "Home",
"__v": 0
},{
"id": {
"cID": "5f15d5b7cb4a6642bddc0fe8"
},
"name": "Garden",
"__v": 0
},{
"id": {
"cID": "5f15d5cdcb4a6642bddc0fe9"
},
"name": "Games",
"__v": 0
}]
//products.json
[{
"_id": {
"$oid": "5f15d8852a025143f9593a7c"
},
"image": "",
"brand": "PS3",
"price": 250,
"rating": 1,
"numReviews": 0,
"isFeatured": true,
"name": "FIFA 20",
"description": "The most hard FIFA ever",
"category": {
"$oid": "5f15d5cdcb4a6642bddc0fe9"
},
"countInStock": 25,
"__v": 0
},{
"_id": {
"$oid": "5f15d92ee520d44421ed8e9b"
},
"image": "",
"brand": "IKEA",
"price": 350.9,
"rating": 5,
"numReviews": 0,
"isFeatured": true,
"name": "Garden Chair",
"description": "beautiful chair for garden",
"category": {
"$oid": "5f15d5b7cb4a6642bddc0fe8"
},
"countInStock": 10,
"__v": 0
},{
"_id": {
"$oid": "5f15d964e520d44421ed8e9c"
},
"image": "",
"brand": "OBI",
"price": 1350.9,
"rating": 5,
"numReviews": 0,
"isFeatured": true,
"name": "Swimming Pool",
"description": "beautiful Swimming Pool for garden",
"category": {
"$oid": "5f15d5b7cb4a6642bddc0fe8"
},
"countInStock": 10,
"__v": 0
},{
"_id": {
"$oid": "5f15d9b3e520d44421ed8e9d"
},
"image": "",
"brand": "OBI",
"price": 490.9,
"rating": 5,
"numReviews": 0,
"isFeatured": true,
"name": "Grass Cut Machine",
"description": "Grass Cut Machine for garden",
"category": {
"$oid": "5f15d5b7cb4a6642bddc0fe8"
},
"countInStock": 5,
"__v": 0
},{
"_id": {
"$oid": "5f15da13e520d44421ed8e9e"
},
"image": "",
"brand": "Mobilix",
"price": 1000,
"rating": 5,
"numReviews": null,
"isFeatured": true,
"name": "Sofa",
"description": "Big Sofa for living room",
"category": {
"$oid": "5f15d5b2cb4a6642bddc0fe7"
},
"countInStock": 2,
"__v": 0
}]
Мой основной код. Функция/компонент фильтра находится в своем собственном.
/* eslint-disable */
import React, { useState, useEffect } from "react";
import "./ProductsPage.css";
import ProductCard from "../Product Card/ProductCard";
import CategoryFilter from "../CategoryFilter/CategoryFilter";
//TESTING DATA
const productData = require("../../../assets/products.json");
const categoriesData = require("../../../assets/categories.json");
function ProductsPage() {
const [products, setProducts] = useState([]);
const [search, setSearch] = useState("");
const [categories, setCategories] = useState([]);
const [productsCategories, setproductsCategories] = useState([]);
const [active, setActive] = useState([]);
const [initialState, setInitialState] = useState([]);
useEffect(() => {
setProducts(productData);
setCategories(categoriesData);
setproductsCategories(productData);
setActive(-1);
setInitialState(productData);
console.log("allproducts", products);
}, []);
//filtering products
const filteredProducts = products.filter((searchedItem) =>
searchedItem.name.toLowerCase().includes(search.toLowerCase())
);
const searchProducts = (event) => {
setSearch(event.target.value);
};
//categories
const changeCategory = (category) => {
{
category === "all"
? [setproductsCategories(initialState), setActive(true)]
: [
setproductsCategories(
products.filter((i) => i.category.cID === category),
setActive(true)
),
];
}
};
return (
<div className='productsPage'>
<div className='productsPage__searchBar-holder'>
<form>
<input
type='text'
placeholder='Search for a product'
className='productsPage__searchBar'
onChange={searchProducts}
/>
</form>
</div>
<CategoryFilter
categories={categories}
categoryFilter={changeCategory}
productsCategories={productsCategories}
active={active}
setActive={setActive}
/>
<div className='productList'>
{filtered`enter code here`Products.map((product) => (
<ProductCard
key={product.id}
title={product.name}
description={product.description}
price={product.price}
image={product.image}
/>
))}
</div>
</div>
);
}
export default ProductsPage;
The CategoryFilter.js file
/* eslint-disable */
import React from "react";
import "./CategoryFilter.css";
function CategoryFilter({
categories,
categoryFilter,
productsCategories,
active,
setActive,
}) {
return (
<div className='categories__holder'>
<button
className={active === -1 ? "category__active" : "category__inactive"}
onClick={() => {
categoryFilter("all"), setActive(-1);
}}
>
All items
</button>
{categories.map((category) => (
<button
key={category.name}
className={active === categories.indexOf(categories) ? "category__active" :
"category__inactive"}
onClick={() => {
// categoryFilter(category.id), setActive(categories.indexOf(category));
console.log(categories);
console.log(categories.indexOf(category));
}}
>
{category.name}
</button>
))}
</div>
);
}
export default CategoryFilter;
Любой совет был бы очень полезен. Я застрял на этом в течение некоторого времени.