[英]How can I filter an array which is in react redux reducer state?
This is my reducer file in react这是我在 react 中的 reducer 文件
const initialState = {
products: [
{
name: 'Icecream',
inCart: false,
num: 2
},
{
name: 'Cake',
inCart: true,
num: 5
}
]
};
export const reducer = (state = initialState, action) => {
switch (action.type) {
case REVERSE:
let newProd = [ ...state.products ];
newProd.filter((a) => {
if (a.inCart === true) {
return a;
}
});
console.log(newProd);
return {
...state,
products: newProd
};
default:
return state;
}
};
and this is the console log of newProd which shows the filter function doesn't work这是 newProd 的控制台日志,显示过滤器 function 不起作用
0: {name: "Icecream", inCart: false, num: 2}
1: {name: "Cake", inCart: true, num: 5}
length: 2
__proto__: Array(0)
How can I filter the products array so I can only get the item that has inCart = true and replace it with the old products array?如何过滤 products 数组,以便我只能获取具有 inCart = true 的项目并将其替换为旧 products 数组?
Filter returns a new array & won't mutate the original one.过滤器返回一个新数组并且不会改变原始数组。 You are filtering but not assigning the output of filter to a variable.您正在过滤但未将过滤器的 output 分配给变量。
Do this做这个
export const reducer = (state = initialState, action) => {
switch (action.type) {
case REVERSE:
let newProd = state.products.filter((a) => { //<---- like this
if (a.inCart === true) {
return a;
}
});
console.log(newProd);
return {
...state,
products: newProd
};
default:
return state;
}
};
You can also do it in a single liner - like this:您也可以在单个衬垫中执行此操作 - 如下所示:
...
case REVERSE:
return {
...state,
products: state.products.filter(a => a.inCart)
};
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.