【发布时间】:2021-09-03 10:35:48
【问题描述】:
我尝试设置以升序或降序方式过滤我的产品的功能。
如果您检查我下面的代码以访问我尝试通过产品映射的每个产品的价格,然后删除美元符号并将其排序为升序,最后设置产品的新状态。
但现在我感到困惑,因为我有排序数组,但在尝试设置产品的新状态时没有整个产品??
感谢您的帮助
const data = [
{
category: "Sporting Goods",
price: "$49.99",
stocked: true,
name: "Football",
},
{
category: "Sporting Goods",
price: "$9.99",
stocked: true,
name: "Baseball",
},
{
category: "Sporting Goods",
price: "$29.99",
stocked: false,
name: "Basketball",
},
{
category: "Electronics",
price: "$99.99",
stocked: true,
name: "iPod Touch",
},
{
category: "Electronics",
price: "$399.99",
stocked: false,
name: "iPhone 5",
},
{ category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7" },
];
export default data;
const App = () => {
const [searchValue, setSearchValue] = useState("");
const [productsInfo, setProductsInfo] = useState([]);
const handleChange = (e) => {
setSearchValue(e.target.value);
};
const selectedChangeFilter = (e) => {
if (e.target.value === "sporting goods") {
const sportingGoods = data.filter(
(product) => product.category === "Sporting Goods"
);
setProductsInfo(sportingGoods);
}
if (e.target.value === "electronics") {
const electronicsGoods = data.filter(
(product) => product.category === "Electronics"
);
setProductsInfo(electronicsGoods);
}
if (e.target.value === "lowest price") {
const lowestPriceGoods = data
.map((product) => product.price.substr(1))
.sort((a, b) => a - b);
console.log(lowestPriceGoods);
setProductsInfo(lowestPriceGoods);
}
if (e.target.value === "all") {
setProductsInfo(data);
}
};
const searchProducts = (products) => {
if (searchValue.toLowerCase().trim() === "") {
setProductsInfo(products);
} else {
const seekedItem = productsInfo.filter(
(product) =>
product.name.toLowerCase().trim().includes(searchValue) ||
product.category.toLowerCase().trim().includes(searchValue)
);
setProductsInfo(seekedItem);
}
};
return (
<div>
<SearchInput
handleChange={handleChange}
searchValue={searchValue}
selectedChangeFilter={selectedChangeFilter}
/>
<Products
data={data}
searchValue={searchValue}
productsInfo={productsInfo}
searchProducts={searchProducts}
/>
</div>
);
};
export default App;
【问题讨论】:
-
你能在codesandbox中分享你的代码吗?
-
这里是codesandbox上的代码@akhtarvahid codesandbox.io/s/bw6sl