网站搜索

reactjs - 我如何解决 useReducer 钩子中的类型错误“argument is not assignable to parameter of type never”?


在我的 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
}

答案#1

在查看完文档后,我发现,reducer 函数传入的是两个参数,而不是你解构的对象。

所以,这一行应该是:

const reducer = (state:TodoState[] = [], action:TodoAction = {}): TodoState[] => {