我是第一次使用 "@reduxjs/toolkit" (版本 "^1.5.1")。
我正在尝试从状态数组 (roundScore) 中删除一个对象。通常可以使用 filter()
很容易地完成此操作。但出于某种原因,这并不起作用,我无法弄清楚原因。这是我的代码:
Reducer 片段:
import { createSlice } from "@reduxjs/toolkit";
export const roundScoreSlice = createSlice({
name: "roundScore",
initialState: {
roundScore: [],
},
reducers: {
deleteArrow: (state, action) => {
console.log(`action.payload = ${action.payload}`); // returns correct id
state.roundScore.filter((arrow) => arrow.id !== action.payload);
},
},
});
export const { deleteArrow } = roundScoreSlice.actions;
export default roundScoreSlice.reducer;
React组件:
import React from "react";
import styled from "styled-components";
import { motion } from "framer-motion";
import { useDispatch } from "react-redux";
import { deleteArrow } from "../../redux-reducers/trackSession/roundScoreSlice";
export default function InputtedScore({
arrowScore,
id,
initial,
animate,
variants,
}) {
const dispatch = useDispatch();
const applyStyling = () => {
switch (arrowScore) {
case 0:
return "miss";
case 1:
return "white";
case 2:
return "white";
case 3:
return "black";
case 4:
return "black";
case 5:
return "blue";
case 6:
return "blue";
case 7:
return "red";
case 8:
return "red";
case 9:
return "gold";
case 10:
return "gold";
default:
return null;
}
};
return (
<ParentStyled
id={id}
initial={initial}
animate={animate}
variants={variants}
onClick={() => dispatch(deleteArrow(id))}
>
<Circle className={applyStyling()}>
{arrowScore}
<IconStyled>
<IoIosClose />
</IconStyled>
<IoIosClose className="redCross" />
</Circle>
</ParentStyled>
);
}
添加2个箭头后的状态如下:
roundScore: [
{
id:"e0f225ba-19c2-4fd4-b2bf-1e0aef6ab4e0"
arrowScore:7
},
{
id:"2218385f-b37a-4f2c-a8db-4e7e65846171"
arrowScore:5
}
]
我尝试了一些组合方式。
- 在dispatch中使用e.target.id
- 在dispatch中使用e.currentTarget.id
- 在dispatch中使用({id})而不是只有(id)
- 在reducer函数中使用或不使用括号包裹,例如在
(state, action) => { /* 代码 */ }
中
非常感谢任何帮助。
deleteArrow
中添加返回过滤器吗? - Viet