reactjs - 更新减速器中的嵌套对象
问题描述
我正在使用 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;
解决方案
转这个
[...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;
推荐阅读
- javascript - React - 能够通过道具控制 SVG 的填充颜色
- image - 如何在 IDL 中的世界地图上绘制轮廓数据?
- python - 如何使用 pandas 中的排序特征顺序生成新特征?
- javascript - vue-router:浏览器尝试打开
作为本地文件 - javascript - Mongo ISODate - 如何检查是否超过 30 天?
- python - 预期二维数组,得到一维数组
- azure - Azure 警报 - 无法找到以前创建和删除的警报
- python - django makemessages - 命令错误:运行 msguniq 时发生错误 - 语法错误
- amazon-web-services - AWS Cognito - 以用户身份进行身份验证
- gitlab-ci - Gitlab CI 管道包括:模板不适用于 Python 项目