如何过滤过滤后的数组?所以,假设我按价格过滤产品。假设输入范围滑块(价格)的值小于1000美元,那么它将返回一个数组,该数组低于所述值(1000美元)。现在,如果我想再次使用品牌或类别过滤器按钮过滤,例如,我从品牌过滤器中选择了品牌‘宜家’。如何从过滤后的价格过滤返回的数组?现在,当我按价格过滤产品时,它可以返回一个数组,但是当我再次按类别/品牌过滤时,它将返回一个不是来自过滤的价格数组的数组。
这是我的密码:
export const state = {
products: [], //this is where I stored all the products coming from the API
filters: {
categories: [], //this is where I stored all the categories
brands: [], //this is where I stored all the brand
price: 0, //this is where I stored the max price from the array
},
};@param值-来自输入范围滑块的整数值
export const loadFilterPrice = function (value) {
return state.products.filter(product => product.price <= value);
};@param类型-字符串值“品牌”或“类别”@param值-品牌/类别的字符串值,
export const loadFilterProductByType = function (type, value) {
if (value === 'all') return state.products;
return state.products.filter(product => product[type] === value);
};发布于 2022-04-09 07:19:44
您筛选了产品,但尚未为过滤产品分配新的变量/状态
您可以在这里添加一个filteredProducts变量
export const state = {
products: [], //this is where I stored all the products coming from the API
filteredProducts: [] //this should be a clone of `products`
filters: {
categories: [], //this is where I stored all the categories
brands: [], //this is where I stored all the brand
price: 0, //this is where I stored the max price from the array
},
};当最初从API调用为products分配值时,也可以为filteredProducts值赋值。
//`respondedProducts` is from API calls
state.products = [...respondedProducts]
state.filteredProducts = [...respondedProducts]以下是我们如何使用它
export const loadFilterPrice = function (value) {
if(!value) return state.products; //return the original product list
return state.filteredProducts.filter(product => product.price <= value);
};state.filteredProducts = loadFilterPrice(1000) //need to update filtered products variable类似地,我们可以将其应用于loadFilterProductByType
export const loadFilterProductByType = function (type, value) {
if (value === 'all') return state.products; //return the original product list
return state.filteredProducts.filter(product => product[type] === value);
};state.filteredProducts = loadFilterProductByType('brand', 'ikea') //need to update filtered products variable至于多个过滤器的情况,我建议您应该有另一个名为state.filterValues的状态
export const state = {
products: [], //this is where I stored all the products coming from the API
filteredProducts: [] //this should be a clone of `products`
filters: {
categories: [], //this is where I stored all the categories
brands: [], //this is where I stored all the brand
price: 0, //this is where I stored the max price from the array
},
filterValues: {
category: 'all',
brand: 'all',
price: 0,
}, initialize filter values mapping
};你也需要重构
const loadFilterProductByType = function (products, type, value) {
if (value === 'all') return products; //return the original product list
return products.filter(product => product[type] === value);
};
const loadFilterPrice = function (products, value) {
if(!value) return products; //return the original product list
return products.filter(product => product.price <= value);
};之后,您可以根据筛选值应用筛选器。
function filter(key, value) {
//possible keys 'price', 'category', 'brand'
state.filterValues[key] = value
let filteredResult = [...state.products] //original list
for(const [key,value] of Object.entries(state.filterValues)) {
if(key === 'price') {
filteredResult = loadFilterPrice(filteredResult, Number(value))
continue
}
loadFilterProductByType(filteredResult, key, value)
}
//update the final result to `filteredProducts`
state.filteredProducts = filteredResult
}以下是我们如何使用它
filter('price', 1000)
filter('category', 'something')
filter('brand', 'ikea')
//reset filter
filter('price', 0)
filter('category', 'all')
filter('brand', 'all')发布于 2022-04-09 08:26:50
这个解决方案特别试图回答以下几个问题:
我该怎么办?
有几种方法可以解决这个问题。最优的方法可能是使用useMemo、useCallback等。
下面仅仅是一种可能的方法,它只依赖于useState和useEffect。
const {useState, useEffect} = React;
const Thingy = ({initState, ...props}) => {
const [products, setProducts] = useState(
[
...initState.products.map(
x => ({...x, filtered: false})
)
]
);
const [filters, setFilters] = useState({
categories: "", brands: "", price: 0 // Number.MAX_VALUE
});
const [showFilters, setShowFilters] = useState(false);
const [filterPrice, setFilterPrice] = useState(0);
const renderFilterFor = col => (
<div>
<label> {col} </label>
<select
name={col}
onChange={e => {
const v = e.target.value;
setFilters(prev => ({
...prev,
[col]: v !== 'None' ? v : ""
}));
}}
>
{
[
'None', ...new Set(products.map(ob => ob[col]))
].map(cat => (
<option value={cat}>{cat}</option>
))
}
</select>
</div>
);
const applyFilter = pr => (
Object.entries(filters)
.filter(([k, v]) => ((k === 'price' && v > 0) || v.length > 0))
.every(([k, v]) => ((k === 'price' && pr[k] <= v) || pr[k] === v))
);
useEffect(
() => setProducts(
prev => prev.map(
p => ({
...p,
filtered: applyFilter(p)
})
)
),
[filters]
);
return (
<div>
<button
onClick={() => setShowFilters(prev => !prev)}
>
{showFilters ? 'Hide' : 'Show'} Filters
</button>
{
showFilters && (
<div class="filtersLine">
<div>{renderFilterFor("categories")}</div>
<div>{renderFilterFor("brands")}</div>
<label for="priceInp">Enter price: </label>
<input
type="number" value={filterPrice} min={0}
onChange={e => {
const v = e.target.value;
setFilterPrice(v);
setFilters(prev => ({
...prev,
price: +v
}));
}}
/>
</div>
)
}
{
products.filter(({filtered}) => filtered).map(
({productId, productName, categories, brands, price}) => (
<div class="singleProduct" key={productId}>
{productName}
<b>Category: </b>{categories}
<b>Brand: </b>{brands}
<b>Price: </b>{price}
</div>
)
)
}
</div>
);
};
const initState = {
products: [...Array(15).keys()].map(i => ({
productId: i+1,
productName: `Product - ${i+1}`,
categories: `Category - ${i % 3 +1}`,
brands: `Brand - ${i % 4 +1}`,
price: Math.floor(Math.random() * ((i+1) * 5))
}))
};
ReactDOM.render(
<div>
DEMO
<Thingy initState={initState}/>
</div>,
document.getElementById("rd")
);.singleProduct {
border: 2px solid grey;
margin: 5px;
width: 85%;
}
.singleProduct > *{
margin: 15px;
padding: 5px;
}
.filtersLine {
display: flex;
margin: 15px;
align-items: center;
justify-content: space-between;
width: 85%;
}
.filtersLine > label { margin: 10px; }<div id="rd" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
发布于 2022-04-11 10:41:19
respectively.
prices.
调用loadFilterPrice和loadFilterProductByType,希望为过滤器提供更易于维护的结构,因此我添加了一个ProductFilter类。
这是一个AND过滤器,所以如果添加(例如)两个类别,filterBy将返回一个空数组。
我还假设您使用的是ES6。
let productsFilterArr = [];
class ProductsFilter { // 2
constructor(type, value) {
this.type = type;
this.value = value;
}
}
const filterBy = function (productsFilterArr, state) { // 1
let filteredState = {...state} // Creates new copy
for (const productFilter of productsFilterArr) {
if (productFilter.type == 'price') {
filteredState.products = loadFilterPrice(productFilter.value, filteredState.products);
} else {
filteredState.products = loadFilterProductByType(productFilter, filteredState.products);
}
}
return filteredState;
}
/* COPIED CODE from sN00b */
var state = { // 3
products: [...Array(15).keys()].map(i => ({
productId: i+1,
productName: `Product - ${i+1}`,
categories: `Category - ${i % 3 +1}`,
brands: `Brand - ${i % 4 +1}`,
price: Math.floor(Math.random() * ((i+1) * 5))
}))
};
/* END: COPIED CODE */
const loadFilterPrice = function (value, products) {
return products.filter(product => product.price <= value)
};
const loadFilterProductByType = function (productFilter, products) {
return products.filter(product => product[productFilter.type] === productFilter.value);
};
/* JUST FOR SHOWCASING */
let filteredStates = {};
productsFilterArr = [new ProductsFilter('brands', 'Brand - 2'), new ProductsFilter('price', 10)];
filteredStates = filterBy(productsFilterArr, state);
console.log({productsFilterArr}, filteredStates);
console.log('-----------------------');
productsFilterArr = [new ProductsFilter('categories', 'Category - 1')];
filteredStates = filterBy(productsFilterArr, state);
console.log({productsFilterArr}, filteredStates)
console.log('-----------------------');
https://stackoverflow.com/questions/71805479
复制相似问题