我有3个操作(add_todo、delete_todo和completed_todo(。添加和删除操作很好,但我应该将删除的项目添加到已完成的列表中,以便在单独的组件中呈现。但每当我尝试使用、筛选或查找删除的项目时,我都会得到一个null值。
减速器代码:
const initialState = {
todos: [],
completed: [],
};
const todoSlice = createSlice({
name: "todos",
initialState,
reducers: {
add_todo(state, action) {
state.todos = [...state.todos, action.payload];
},
delete_todo(state, action) {
state.todos = state.todos.filter((todo) => todo.id !== action.payload);
},
completed_todo(state, action) {
console.log(state.todos.find((todo) => todo.id === action.payload));
state.completed = [
...state.completed,
state.todos.filter((todo) => todo.id === action.payload),
];
},
},
});
export const todoActions = todoSlice.actions;
export const selectTodo = (state) => state.todos.todos;
export default todoSlice.reducer;
调用或调度操作的代码:
function TodoList() {
const dispatch = useDispatch();
const todos = useSelector(selectTodo);
const handleDelete = (id) => {
dispatch(todoActions.delete_todo(id));
dispatch(todoActions.completed_todo(id));
};
// Some code and a button with handleDelete
}
操作将被一个接一个地调度。在您的第一个操作dispatch(todoActions.delete_todo(id));
之后,您将从您的状态.filter((todo) => todo.id !== action.payload)
中删除todo。
之后,第二个动作get被分派dispatch(todoActions.completed_todo(id));
。但是state.todos.find((todo) => todo.id === action.payload)
找不到它,因为它已经被删除了。
为了解决这个问题,你可以交换你的调度电话。首先完成它,然后删除它。问题解决了:-(
这里的问题是,当您调度操作以获得已完成的列表时,您已删除的待办事项已经从状态中消失。而不是调度2个操作。您可以按照delete todo
操作中的要求执行操作。
delete_todo(state, action) {
// find the todo to delete
const deletedTodo = state.todos.find((todo) => todo.id === action.payload);
state.completed = [
...state.completed,
deletedTodo,
];
state.todos = state.todos.filter((todo) => todo.id !== action.payload);
},
因为你完成的todo只是你试图删除的todo。IMHO在我们用来调度删除todo的相同操作中执行它是合乎逻辑的。