這是我的代碼框鏈接。https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js在此過濾中,當我單擊最高價格時,它會正確顯示,當我再次單擊所有過濾器時,我該如何設定回到原來的狀態。請為此提供任何解決方案。
import React, { useState } from "react";
import Products from "./Components/Products/Products";
import SearchInput from "./Components/SearchInput/SearchInput";
import data from "./utils/data";
const App = () => {
const [searchValue, setSearchValue] = useState("");
const [productsInfo, setProductsInfo] = useState([]);
const handleChange = (e) => {
setSearchValue(e.target.value);
};
const selectedChangeFilter = (e) => {
const { value } = e.target;
if (value === "sporting goods") {
const sportingGoods = data.filter(
(product) => product.category === "Sporting Goods"
);
setProductsInfo(sportingGoods);
}
if (value === "electronics") {
const electronicsGoods = data.filter(
(product) => product.category === "Electronics"
);
setProductsInfo(electronicsGoods);
}
if (value === "lowest price") {
const lowestPriceGoods = data.sort((el1, el2) =>
el1.price.localeCompare(el2.price, undefined, { numeric: true })
);
setProductsInfo([...lowestPriceGoods]);
}
if (value === "highest price") {
const highestPriceGoods = data.sort((el1, el2) =>
el2.price.localeCompare(el1.price, undefined, { numeric: true })
);
setProductsInfo([...highestPriceGoods]);
}
if (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;
uj5u.com熱心網友回復:
代替:
if (value === "all") {
const copiedData = [...data]
setProductsInfo(copiedData);
}
uj5u.com熱心網友回復:
javascript中對陣列的排序函式會修改原始陣列。這就是為什么在修改原始資料陣列時進行最高或最低排序時無法回傳原始狀態的原因。而是執行以下操作:
if (value === "lowest price") {
const lowestPriceGoods = [...data];
lowestPriceGoods.sort((el1, el2) =>
el1.price.localeCompare(el2.price, undefined, { numeric: true })
);
setProductsInfo(lowestPriceGoods);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466521.html
標籤:反应
