Redux 动作触发两次

Redux action fires twice

我有这个 redux todo 应用程序,它根据未完成任务的数量更新剩余任务的状态。

该应用程序运行正常,没有任何错误或问题,但是当我添加任务、切换完成和删除任务时,remainingTasks/updateRemainingTasks 的操作类型会触发两次:

有趣的是,该操作仅在删除已完成的任务时触发一次:

这些是该切片及其对应组件的代码:

切片

import { createSlice } from "@reduxjs/toolkit";

const remainingTasksSlice = createSlice({
  name: "remainingTasks",
  initialState: 0,
  reducers: {
    updateRemainingTasks: (state, action) => {
      return action.payload;
    },
  },
});

// Selectors
export const selectRemainingTasksSlice = (state) => state.remainingTasksReducer;

// Actions
export const { updateRemainingTasks } = remainingTasksSlice.actions;

// Reducers
export default remainingTasksSlice.reducer;

组件

import { useSelector, useDispatch } from "react-redux";
import {
  selectRemainingTasksSlice,
  updateRemainingTasks,
} from "./remainingTasksSlice";
import { selectTaskSlice } from "../task/taskSlice";

const RemainingTasks = () => {
  const dispatch = useDispatch();
  const remainingTasksSlice = useSelector(selectRemainingTasksSlice);
  const taskSlice = useSelector(selectTaskSlice);

  // Number of Incomplete Tasks
  const incompleteTasks = taskSlice.filter((task) => !task.completed).length;

  // Update the State of the Remaining Tasks
  dispatch(updateRemainingTasks(incompleteTasks));

  return (
    <div>
      <h1 className="header">
        {remainingTasksSlice > 1
          ? `${remainingTasksSlice} Tasks Left`
          : `${remainingTasksSlice} Task Left`}
      </h1>
    </div>
  );
};

export default RemainingTasks;

我想知道这是正常现象还是我的代码没有优化好。

我认为你必须将 dispatch 调用到 useEffect 挂钩中:

....
useEffect(()=>{
    // Number of Incomplete Tasks
    const incompleteTasks = taskSlice.filter((task) => !task.completed).length;
    // Update the State of the Remaining Tasks
    dispatch(updateRemainingTasks(incompleteTasks));
}, [taskSlice]);
....

否则每次渲染组件时都会调用 dispatch。