【发布时间】:2021-07-31 08:30:02
【问题描述】:
将鼠标悬停在我的useReducer 函数中的todos 变量上:
const [state, dispatch] = useReducer(reducer, todos);
给出以下类型错误。
Argument of type 'TodoState[]' is not assignable to parameter of type 'never'.
我尝试在 reducer 函数中添加 TodoState[] 作为返回类型,以确保不会意外返回 never[],但是错误仍然存在:
以下是相关代码:
interface TodoState {
id: string;
}
interface TodoAction {
type?: 'CREATED' | 'DELETED' | 'UPDATED';
payload?: TodoState;
}
interface TodoReducer {
state: TodoState[];
action: TodoAction;
}
interface TodosProviderProps {
children: ReactChildren;
todos: TodoState[];
}
const reducer = ({ state = [], action = {} }: TodoReducer): TodoState[] => {
const { payload, type } = action;
const mutatedItem = payload;
if (!mutatedItem) {
return state;
}
const mutatedIndex = state.findIndex((item) => item.id === mutatedItem.id);
switch (type) {
case 'CREATED':
if (mutatedIndex < 0) {
state.push(mutatedItem);
}
break;
case 'DELETED':
if (mutatedIndex >= 0) {
state.splice(mutatedIndex, 1);
}
break;
case 'UPDATED':
state[mutatedIndex] = mutatedItem;
break;
default:
return state;
}
return state;
};
export function TodosProvider({ children, todos }: TodosProviderProps) {
const [state, dispatch] = useReducer(reducer, todos);// type error for todos here
// rest of code
}
【问题讨论】:
-
如果对您有用,请不要忘记为答案投票
标签: reactjs typescript use-reducer