gpt4 book ai didi

javascript - 如何使用 React 动态处理多个过滤器?

转载 作者:行者123 更新时间:2023-12-02 22:42:08 25 4
gpt4 key购买 nike

我目前正在经营一家在线商店,该商店根据尺寸、库存、性别等特定标准过滤产品。

虽然我已经能够让它在一定程度上发挥作用。我的程序目前按尺寸、性别、按价格排序等进行过滤。但是,我无法让它按品牌进行过滤。由于某种原因,一旦我单击该品牌,我就可以过滤该功能一次,但是,一旦我单击另一个品牌,该特定品牌的过滤器就不会运行。

这是代码沙箱的链接:

https://codesandbox.io/s/mystifying-roentgen-7mp0t

我目前一直坚持按品牌过滤,我尝试通过检查该品牌是否包含在项目中并使用 localeCompare() 来将过滤结果与单击的项目的状态进行比较。

这是代码沙箱的链接:

https://codesandbox.io/s/mystifying-roentgen-7mp0t

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
});

};

一旦点击某个项目,我希望能够通过此功能按品牌进行过滤。

这是代码沙箱的链接:

https://codesandbox.io/s/mystifying-roentgen-7mp0t

最佳答案

您的申请中有 2 个错误:

1) 第一个是 @user753642 在对您的问题的评论中报告的,请从 index.js 中删除此行,因为它将您所有产品的 brand 设置为“”:

console.log(product.brand = this.state.brand)

2) 您正在过滤filteredProducts,而不是所有产品。虽然在第一次过滤品牌后,filterdProducts 没有任何其他品牌的商品,但在过滤另一个品牌后,它会返回一个空集合。更改 index.jshandleFormSubmit 中的行,来自:

const shallowCopy = [...this.state.filteredProducts];

至:

const shallowCopy = [...this.state.products];

关于javascript - 如何使用 React 动态处理多个过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58551296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com