我有一个这样的数据结构:
const dataObj = {
myparam: 'Hello',
data: [
{
id: 1, checked: false
},
{
id: 2, checked: true
}
{
id: 3, checked: false
}
]
}
我一直在尝试useReducer
,因为我想更新我的arrayList,这样当我发送我的有效载荷时,我可以改变id为1的对象被检查/未检查。
我这样解决了这个问题:
const reducer = (state: StateType, action: Action) => {
const { type, payload } = action;
let newArrayChecked: Array<DataItems> = [];
let newArrayUnchecked: Array<DataItems> = [];
switch (type) {
case ActionKind.Checked:
newArrayChecked = state.items.map((item) => {
const it = item;
if (item.id === payload.id) it.checked = true;
return it;
});
return {
...state,
items: newArrayChecked,
};
case ActionKind.UnChecked:
newArrayUnchecked = state.items.map((item) => {
const it = item;
if (item.id === payload.id) it.checked = false;
return it;
});
return {
...state,
items: newArrayUnchecked,
};
default:
return state;
}
};
我对此不太高兴,因为对于初学者来说,它的代码或多或少是重复的,看起来很丑。我想知道是否有更好的方法来做到这一点与useReducer?我对这个Hook相当陌生,正在寻找代码优化。
你只需像这样更新:
case ActionKind.Checked:
newArrayChecked = state.items.map((item) => {
return {
...item,
checked: item.id === payload.id ? true: item.checked
};
});
return {
...state,
items: newArrayChecked,
};
case ActionKind.UnChecked:
newArrayChecked = state.items.map((item) => {
return {
...item,
checked: iitem.id === payload.id ? false : item.checked
};
});
return {
...state,
items: newArrayUnchecked,
};