Javascript 如何使用react动态处理大量过滤器?
我目前在一家在线商店工作,该商店根据一定的标准过滤产品,如大小、库存、性别等 虽然我已经能够使它在一定程度上发挥作用。我的程序目前按大小、性别、价格等进行过滤。但是,我无法按品牌进行过滤。出于某种原因,一旦我点击该品牌,我就能够过滤该功能一次,但是,一旦我点击另一品牌,该特定品牌的过滤器就不会运行 以下是代码沙盒的链接: 我目前一直坚持按品牌进行筛选,并尝试通过检查项目中是否包含品牌以及使用localeCompare()将筛选结果与单击项目的状态进行比较 以下是代码沙盒的链接: 我希望能够通过这个功能过滤品牌,一旦点击一个项目 以下是代码沙盒的链接:Javascript 如何使用react动态处理大量过滤器?,javascript,reactjs,redux,filter,react-redux,Javascript,Reactjs,Redux,Filter,React Redux,我目前在一家在线商店工作,该商店根据一定的标准过滤产品,如大小、库存、性别等 虽然我已经能够使它在一定程度上发挥作用。我的程序目前按大小、性别、价格等进行过滤。但是,我无法按品牌进行过滤。出于某种原因,一旦我点击该品牌,我就能够过滤该功能一次,但是,一旦我点击另一品牌,该特定品牌的过滤器就不会运行 以下是代码沙盒的链接: 我目前一直坚持按品牌进行筛选,并尝试通过检查项目中是否包含品牌以及使用localeCompare()将筛选结果与单击项目的状态进行比较 以下是代码沙盒的链接: 我希望能够通
应用程序中有两个错误: 1) 第一个是@user753642在对您的问题的评论中报告的,请从
index.js
中删除这一行,因为它将所有产品的品牌设置为”
:
console.log(product.brand=this.state.brand)
2) 您正在筛选filteredProducts
,没有筛选所有产品。在对品牌进行首次筛选后,filterdProducts
没有任何其他品牌的项目,但在对其他品牌进行筛选后,它返回一个空集合。将index.js
中的handleFormSubmit
中的行更改为:
const shallowCopy=[…this.state.filteredProducts];
致:
constshallowcopy=[…this.state.products];
除非我弄错了,否则在第549行,您分配了console.log(product.brand=this.state.brand)
这是双重错误:您默默地分配了内容(您应该使用逗号来记录),而this.state.brand
是无效的(因此此后您的所有产品都会被过滤掉)。通过实际删除console.log,我似乎可以通过brandAwesome dude进行过滤,我只是出于调试目的使用它,但我没有意识到它导致的奇怪错误。我很感激,伙计!这绝对解决了问题。非常感谢老板!
createCheckboxes = () => available_sizes.map(this.createCheckbox);
handleFormSubmit = event => {
//4) this button updates the filters on the sizes, which I think I need to fix to update the brands, the price and the gender
event.preventDefault();
//5) right here I am storing the selected checkboxes which is what I was doing before by pushing the checkboxes
const selectedSizes = [...this.selectedCheckboxes];
const shallowCopy = [...this.state.filteredProducts];
let filteredProducts = shallowCopy.filter(product =>
selectedSizes.every(size =>
product.stock.some(s => s.stock > 0 && s.size === size)
)
);
let filteredGender = filteredProducts.filter(product => {
return product.gender.some((item, idx, arr) => {
return item[this.selectedGender] === false ? null : product;
});
});
//***this is the function that is not currently running***//
let filteredData = filteredGender.filter(product => {
//console.log(product.brand.includes(this.state.activeBrand))
//console.log(product.brand = this.state.brand)
return product.brand.includes(this.state.activeBrand)
});
let sortedPrice = filteredData.sort((a, b) => {
return this.state.sortBy === "min"
? a.price - b.price
: b.price - a.price;
});
this.setState({
filteredProducts: sortedPrice
});
};