Redux的状态没有改变

时间:2020-09-24 19:47:56

标签: reactjs redux

我有这个简化程序,它具有初始状态和一系列计划,这些计划具有一系列的访问和一系列的处理方法。 这个想法是当动作(Remove_treatment)触发时,它会删除以下一种处理方式:

import { REMOVE_TREATMENT } from "./treatmentPlanTypes";

const initialState = {
  plans: [
    {
      id: 1,
      visits: [
        {
          id: 1,
          treatments: [
            {
              id: 1,
              name: "treatment1",
            },
            {
              id: 2,
              name: "treatment2",
            },
          ],
        },
        {
          id: 2,
          treatments: [
            {
              id: 1,
              name: "treatment1",
            },
            {
              id: 2,
              name: "treatment2",
            },
          ],
        },
      ],
    },
  ],
};

const treatmentPlanReducer = (state = initialState, action) => {
  switch (action.type) {
    case REMOVE_TREATMENT:
      let clonePlans = [...state.plans];

      const visitIndex = clonePlans[0].visits.findIndex(
        (i) => i.visitId === action.visitId
      );

      const treatmentIndex = clonePlans[0].visits[
        visitIndex
      ].treatments.findIndex((i) => i.treatmentId === action.treatmentId);

      clonePlans[0].visits[visitIndex].treatments.splice(treatmentIndex, 1);
      console.log(JSON.stringify(clonePlans));
      return {
        ...state,
        plans: [...clonePlans],
      };
    default:
      return state;
  }
};

当我console.log(clonePlans)时,我得到了正确的数组。

但是当我返回值时:

返回{ ...州, 计划:[... clonePlans], };

我仍然有旧计划,并且未在组件中进行更新。 如果我尝试直接在上述return语句中从console.log获取输入预期的计划,则该组件将成功更新。

这是我的代码中组件的一部分:

  const plans = useSelector((state) => state.treatmentPlan.plans, shallowEqual)
  const listOfPlans = plans.map((plan) => (
    <PlanArea key={plan.planId} visits={plan.visits} />
  ));
  console.log(listOfPlans);

该组件仍在显示旧计划,但console.log(listOfPlans)显示正确的数组。

1 个答案:

答案 0 :(得分:0)

您需要深入复制计划数组,以使组件能够感觉到状态的变化,从而重新渲染

let clonePlans = JSON.parse(JSON.stringify(state.plans))
return { ...state, plans: clonePlans };