首页 > 解决方案 > 更新减速器中的嵌套对象

问题描述

我正在使用 react、typescript、redux 来创建一个简单的应用程序来管理我的成分,但不知何故我无法用我的代码来管理它。我有以下内容:

我在此文件 types.ts 中声明的类型:

export interface Mytype {
  a: number;
  b: number;
  c: number;
  d: number;
}

export interface Mytype2 {
  Mytypes: Mytype[];
}

export const ADD = "INGREDIENT";
export const DELETE = "INGREDIENT";

interface AddA {
  type: typeof ADD;
  aName: Mytype;
}

interface DeleteA {
  type: typeof DELETE;
  aName: Mytype;
}

export type OrderActionTypes = AddA | DeleteA;

标签: reactjstypescriptreduxreact-redux

解决方案


转这个

[...action.ingredientName]: state.ingredients[action.ingredientName] + 1

进入这个

[action.ingredientName]: state.ingredients[action.ingredientName] + 1

并删除您的DELETE案例中的数组,因为初始状态是一个对象而不是数组。

case DELETE_INGREDIENT:
      return {
          ...state, 
        [action.ingredientName]: state[action.ingredientName] - 1
          
      };

并在此处更改您的类型

import {
  Ingredient,
  ADD_INGREDIENT,
  DELETE_INGREDIENT,
  OrderActionTypes,
} from "./types";

export function addIngredient(newIngredient: keyof Ingredient): OrderActionTypes {
  return {
    type: ADD_INGREDIENT,
    ingredientName: newIngredient,
  };
}

export function deleteIngredient(Ingredient: keyof Ingredient): OrderActionTypes {
  return {
    type: DELETE_INGREDIENT,
    ingredientName: Ingredient,
  };
}

在你的类型中

export interface Ingredient {
  cheese: number;
  bacon: number;
  mushrooms: number;
  ananas: number;
}

export const ADD_INGREDIENT = "ADD_INGREDIENT";
export const DELETE_INGREDIENT = "DELETE_INGREDIENT";

interface AddIngredientAction {
  type: typeof ADD_INGREDIENT;
  ingredientName: keyof Ingredient;
}

interface DeleteIngredientAction {
  type: typeof DELETE_INGREDIENT;
  ingredientName: keyof Ingredient;
}

export type OrderActionTypes = AddIngredientAction | DeleteIngredientAction;

推荐阅读