Redux 删除减速器过滤器方法不起作用

eth*_*her 1 typescript reactjs redux material-ui

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

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

并从我的前端调用它,如下所示:

{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>
  );
})}
Run Code Online (Sandbox Code Playgroud)

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

Dre*_*ese 5

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

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

此外,由于您正在改变这个数组,您将希望使用数组索引作为 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>
  );
})}
Run Code Online (Sandbox Code Playgroud)