reactjs 没有匹配此调用的重载使用useReducer错误

gcuhipw9  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(95)
`import React, {
  JSX,
  createContext,
  useContext,
  useReducer,
  useEffect,
} from "react";
import reducer from "./Reducer";
import { actions } from "./Action";
import cartItems from "../data";

//React Element
interface ReactEl {
  children: JSX.Element[] | JSX.Element;
}
interface ContextState {
  id: string;
  title: string;
  price: string;
  img: string;
  amount: number;
}

export interface IContext {
  loading: boolean;
  cart: Map<
    string,
    {
      id: string;
      title: string;
      price: string;
      img: string;
      amount: number;
    }
  >;
  clearCart: () => void;
}

const AppContext = createContext({} as IContext);

const initialState = {
  loading: false,
  cart: new Map<
    string,
    {
      id: string;
      title: string;
      price: string;
      img: string;
      amount: number;
    }
  >(cartItems.map((item) => [item.id, { ...item }])),
};

const AppProvider = ({ children }: ReactEl) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  function clearCart() {
    dispatch({ type: actions.clear });
  }

  return (
    <AppContext.Provider value={{ ...state, clearCart }}>
      {children}
    </AppContext.Provider>
  );
};

//Use Global Hook
export const useGlobalContext = () => useContext(AppContext);

export default AppProvider;

动作和还原器文件动作和还原器文件

export enum actions {
      clear = "CLEAR_CART",
      increase = "INCREASE",
      decrease = "DECREASE",
      remove = "REMOVE",
      loading = "LOADING",
      display_items = "DISPLAY_ITEMS",
    }
    
    import { actions } from "./Action";
    import { IContext } from "./Context";
    //interface
    interface actionType {
      type: actions;
    }
    const reducer = (state: IContext, action: actionType) => {
      if (action.type === actions.clear) {
        return { ...state, cart: new Map() };
      }
      throw new Error(`No matching type found: ${action.type}`);
    };
    
    export default reducer;

我不断地得到一个错误突出显示在下面的部分突出显示和错误状态没有重载匹配这个调用。我不能理解尝试了很多,但没有任何工作。其次,我怎么知道这种错误状态,因为它花了我相当长的时间,但仍然没有任何工作。是不是因为我贴的“初始状态”

`  const [state, dispatch] = useReducer(reducer, initialState);

  function clearCart() {
    dispatch({ type: actions.clear });
  }`
qvtsj1bj

qvtsj1bj1#

问题来自IContext。您将其定义如下

export interface IContext {
  loading: boolean;
  cart: Map<
    string,
    {
      id: string;
      title: string;
      price: string;
      img: string;
      amount: number;
    }
  >;
  clearCart: () => void;
}

但是你的initialState缺少clearCart。你可以添加一个默认的noop函数。

const initialState = {
  loading: false,
  cart: new Map<
    string,
    {
      id: string;
      title: string;
      price: string;
      img: string;
      amount: number;
    }
  >(cartItems.map((item) => [item.id, { ...item }])),
  clearCart: () => {},
};

相关问题