【问题标题】:How do I solve the type error "argument is not assignable to parameter of type never" for useReducer hook?如何解决 useReducer 挂钩的类型错误“参数不可分配给从不类型的参数”?
【发布时间】: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


【解决方案1】:

查看文档后,我发现,reducer 函数传递了两个参数,而不是您已解构的对象。

所以,该行应该是:

const reducer = (state:TodoState[] = [], action:TodoAction = {}): TodoState[] =&gt; {

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2021-11-20
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多