当我在数组中使用 find 时得到 null - redux

I get null when i use find in an array - redux

我有 3 个操作(add_todo、delete_todo、completed_todo)。添加和删​​除工作正常,但我应该将已删除的项目添加到完成的列表中,以便在单独的组件中呈现它。但是每当我尝试使用、过滤或查找以获取已删除的项目时,我都会得到一个空值。

减速器代码:

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 
}

这里的问题是当您调度操作以获取已完成列表时,您删除的待办事项已经从状态中消失了。而不是分派 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);
    },

因为您完成的待办事项只不过是您要删除的待办事项。恕我直言,在我们用来分派删除待办事项的同一操作中执行此操作是合乎逻辑的。

动作会陆续派发。在您的第一个操作 dispatch(todoActions.delete_todo(id)); 之后,您将从您的状态 .filter((todo) => todo.id !== action.payload).

中删除待办事项

之后,第二个动作被调度 dispatch(todoActions.completed_todo(id));。但是 state.todos.find((todo) => todo.id === action.payload) 找不到它,因为它已经被删除了。

要修复它,您可以交换派遣电话。首先完成它,然后将其删除。问题已解决:-)