gpt4 book ai didi

javascript - 如何使用 useReducer 更新嵌套数组?

转载 作者:行者123 更新时间:2023-12-04 07:16:56 26 4
gpt4 key购买 nike

我有这些:

export type DataItemChild = {
id: number;
title:string;
checked?: boolean;
};
请注意,子项可以在此处未定义:
export type DataItems = {
id: number;
title:string;
subItems?: Array<DataItemChild>;
checked?: boolean;
};

export const initalState: StateType = {
items: [],
date: new Date(),
};
到目前为止,我已经弄清楚如何更新顶级对象上的数组,例如:
  case ActionKind.Checked:
newArrayChecked = state.items.map((item) => ({
...item,
checked: item.id === payload.id ? true : item.checked,
}));
return {
...state,
items: newArrayChecked,
};
我不知道如何更新子项目?我有这个(拆下来)
export const reducer = (state: StateType, action: Action) => {
const { type, payload } = action;
let newArrayChildCheck: Array<DataItemChild> = []
switch (type) {

case ActionKind.UnCheckedSub:
newArrayChildCheck = state.items.map((item) => ({
...item.subItems?.map((sub, index) => ({
checked: sub.id === payload.subItems?[index].id ? true: sub.checked
})),
}));
return {
...state,
items.subItems: newArrayChildCheck,
};

default:
return state;
}
};
但这给了我一个 typescript 错误,说我的 newArrayChildCheck 不支持未定义。完整错误:

Type '{ [x: number]: { checked: boolean | undefined; }; length?:number | undefined; toString?: (() => string) | undefined;toLocaleString?: (() => string) | undefined; pop?: (() => { checked:boolean | undefined; } | undefined) | undefined; ... 29 more ...;[Symbol.unscopables]?: (() => { ...; }) | undefined; }[]' is notassignable to type 'DataItemChild[]'. Type '{ [x: number]: {checked: boolean | undefined; }; length?: number | undefined;toString?: (() => string) | undefined; toLocaleString?: (() => string)| undefined; pop?: (() =


编辑:
在@Kelvin Schoofs 回答之后,我意识到我正在发送一个包含其子项目的整个对象。有效载荷的类型是 DataItems我根据@Kelvin Schoofs 的建议稍微修改了我的尝试:
  newArrayChildCheck = state.items.map((item) => ({
...item,
subItems: item.subItems?.map((sub, index) => ({
...sub,
checked: sub.id === payload.subItems[index].id ? true : sub.checked
})),
不是 [index]但我越来越

object is possible undefined

最佳答案

看起来你传播新对象是错误的。您的 .map((item) => ...)返回一个对象,但在其中传播一个(潜在的)数组,该数组只会填充数字(好吧,字符串化版本)键。您可能打算复制 item 中的原始字段如 idtitle ,并分配映射的 subItems结果到 subItems field 。您在 subItems?.map 中创建的对象同上.像这样的东西是类型正确的:

newArrayChildCheck = state.items.map((item) => ({
...item,
subItems: item.subItems?.map((sub) => ({
...sub,
checked: sub.id === payload.id ? true : sub.checked
})),
}));
那就是如果您想要更改版本的 DataItems大批。如果你真的想返回每个 DataItemChildchecked版本已更改,您可以使用 flatMap像这样:
newArrayChildCheck = state.items.flatMap((item) => 
item.subItems?.map((sub) => ({
...sub,
checked: sub.id === payload.id ? true : sub.checked
})),
);

关于javascript - 如何使用 useReducer 更新嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68705170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com