Redux去除减速器过滤方法不工作



我正在尝试使用过滤器方法从数组中删除一个项目,如下所示:

removeDisplate: (state, action: PayloadAction<string>) => {
console.log(action.payload);
state.map((item) => {
console.log(item.name);
});
state.filter((item) => item.name !== action.payload);
},

从我的前端调用它,像这样:

{cart.map((displate, index) => {
return (
<Card
sx={{
minHeight: "150px",
display: "flex",
padding: "10px",
gap: "10px",
backgroundColor: "black",
margin: "10px",
position: "relative",
}}
key={index}
>
<CloseIcon
sx={{
position: "absolute",
top: "10px",
right: "10px",
color: "red",
cursor: "pointer",
}}
onClick={() => handleRemoveDisplate(displate.name)}
/>
</Card>
);
})}

有效载荷和状态项的名称与控制台日志相同,但它仍然没有从数组中删除它,有什么想法吗?

Array.prototype.filter不会改变它操作的数组,它返回一个new数组,删除谓词回调失败的元素。在切片减速器中,您可以只返回过滤当前状态的结果作为下一个状态值。

removeDisplate: (state, action: PayloadAction<string>) => {
return state.filter((item) => item.name !== action.payload);
},

另外,由于您正在改变这个数组,您将希望而不是使用数组索引作为React键。使用与您正在映射的数据更为内在的值,如id属性。

的例子:

{cart.map((displate, index) => {
return (
<Card
sx={{
minHeight: "150px",
display: "flex",
padding: "10px",
gap: "10px",
backgroundColor: "black",
margin: "10px",
position: "relative",
}}
key={displate.id} // <-- or any unique property among sibling elements
>
<CloseIcon
sx={{
position: "absolute",
top: "10px",
right: "10px",
color: "red",
cursor: "pointer",
}}
onClick={() => handleRemoveDisplate(displate.name)}
/>
</Card>
);
})}

最新更新