我需要按某些情况的顺序更新过滤器。
在某些数据条件下,我需要从数组中删除 1 项。
这是代码
useEffect(() => {
let canceled = false;
const filters = [
new CheckFilterBuilder('badges', 'Badges'),
new CategoryFilterBuilder('category', 'Categories'),
new RangeFilterBuilder('price', 'Price'),
new CheckFilterBuilder('brand', 'Brand'),
];
console.log(filters);
dispatch({ type: 'FETCH_PRODUCTS_LIST' });
shopApi.getProductsList(
state.options,
{ ...state.filters, category: categorySlug }, filters,
).then((productsList) => {
if (canceled) {
return;
}
dispatch({ type: 'FETCH_PRODUCTS_LIST_SUCCESS', productsList });
});
return () => {
canceled = true;
};
}, [dispatch, categorySlug, state.options, state.filters]);
我尝试了使用 if() 语句的解决方案,但无法将其放入我想要的删除项目中
new RangeFilterBuilder('price', 'Price'),
因为它不接受 if() 或其他任何东西,我无法做到这一点。
最佳答案
您可以通过创建一个空的过滤器(或已包含已知的过滤器)并根据条件添加(推送
)其他过滤器来实现此目的
const filters = [new CheckFilterBuilder('badges', 'Badges')];
if (condition === true) {filters.push(new CategoryFilterBuilder('category', 'Categories'))}
if (condition === true) {filters.push(new RangeFilterBuilder('price', 'Price'))}
if (condition === true) {filters.push(new CheckFilterBuilder('brand', 'Brand'))}
关于javascript - 在某些情况下从数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68089395/