我有一个包含以下操作的列表:
useReducer()
函数将对象useReducer()
函数从数组中useReducer()
我需要最佳安全的方式来更新我的列表。
目前,我已经完成了以下操作,但无法正常工作。
const reducer = (state, {type, value}) => {
switch(type){
case 'replacenewarray':
return value;
case 'additem':
return {...state, value}
case 'removeitem':
return state.filter(item => item.room !== value);
default:
return state;
}
}
我的功能组件如下:
const newArray = [
{room: 'someroomid1', ....},
{room: 'someroomid2', ....},
{room: 'someroomid3', ....}
];
const itemToAdd = {room: 'someroomid4', ....};
const itemToRemoveWithRoomId = 'someroomid2';
export const Group = memo(props=> {
const [list, setList] = useReducer(reducer, []);
setList({type: 'replacenewarray', value: newArray});
setList({type: 'additem', value: itemToAdd});
setList({type: 'removeitem', value: itemToRemoveWithRoomId});
});
答案 0 :(得分:1)
根据您的代码,您的状态为Array
,请确保从useReducer
返回类型时保留类型:
const reducer = (state, { type, value }) => {
switch (type) {
case 'replacenewarray':
// v Array as intended
return value;
case 'additem':
// v Fix it to return an array
return [...state, value];
// v Object
// return {...state, value}
case 'removeitem':
// v Array as intended
return state.filter(item => item.room !== value);
default:
return state;
}
};
此外,您必须返回ReactElement
或Group
不会被视为功能组件。
export const Group = memo(props => {
...
return <>Some React Element</>;
});