Reactjs 使用redux toolkit从数组中删除值
我不熟悉使用“@reduxjs/toolkit”(版本“^1.5.1”) 我正在尝试从状态数组(roundScore)中删除对象。这通常是使用Reactjs 使用redux toolkit从数组中删除值,reactjs,react-redux,redux-toolkit,Reactjs,React Redux,Redux Toolkit,我不熟悉使用“@reduxjs/toolkit”(版本“^1.5.1”) 我正在尝试从状态数组(roundScore)中删除对象。这通常是使用filter()非常简单的操作。出于某种原因,这不起作用,我也不明白为什么。这是我的密码: 减速器片: import { createSlice } from "@reduxjs/toolkit"; export const roundScoreSlice = createSlice({ name: "roundSc
filter()
非常简单的操作。出于某种原因,这不起作用,我也不明白为什么。这是我的密码:
减速器片:
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;
反应组分:
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>
);
}
我试过多种方法
- 在调度中使用e.target.id
- 在调度中使用e.currentTarget.id
- 在分派中使用({id})而不是仅使用(id)
- 使用大括号或不使用大括号包装减速器函数,例如在
(状态、操作)=>{/*code*/}
非常感谢您的帮助。好的,看起来问题在于filter方法的工作方式,它返回一个新数组,并且初始数组没有发生变化(这就是为什么我们以前一直使用filter来操作redux状态),您在代码中也显示了未分配给状态的任何属性的筛选操作的值 您需要分配值或修改数组,因此下面的代码应该适合您
state.roundScore = state.roundScore.filter((arrow) => arrow.id !== action.payload);
更改现有阵列:
state.roundScore.splice(state.roundScore.findIndex((arrow) => arrow.id !== action.payload), 1);
是否尝试在
deleteArrow
中添加返回筛选器?谢谢。第一个建议非常有效。根据您的第二个建议,“a”(如“a.findIndex”)没有定义。当然,它应该是一个数组,而不是一个数组,您正在尝试对state.roundScore.findIndex((箭头)
state.roundScore.splice(state.roundScore.findIndex((arrow) => arrow.id !== action.payload), 1);