反应上下文打字稿问题

时间:2020-10-04 03:34:24

标签: javascript reactjs typescript next.js

这是我的AppContext.tsx

sample

MyComponent.tsx

import React, { useState, createContext } from "react";
import { Iitem } from "../utils/interfaces";
interface AppContext {
  showModal: boolean;
  setShowModal: React.Dispatch<React.SetStateAction<boolean>>;
  cart: Array<Iitem>;
  setCart: React.Dispatch<React.SetStateAction<never[]>>;
  currentSelection: object | null;
  setCurrentSelection: React.Dispatch<React.SetStateAction<null>>;
}
export const AppContext = createContext<AppContext>({
  showModal: false,
  setShowModal: () => {},
  cart: [],
  setCart: () => {},
  currentSelection: null,
  setCurrentSelection: () => {},
});

export const AppState: React.FC = ({ children }) => {
  const [showModal, setShowModal] = useState(false);
  const [cart, setCart] = useState([]);
  const [currentSelection, setCurrentSelection] = useState(null);
  return (
    <AppContext.Provider
      value={{
        showModal,
        setShowModal,
        cart,
        setCart,
        currentSelection,
        setCurrentSelection,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

当我尝试调用const MyComponent = () => { const {setCart} = useContext(AppContext); const myFunc = () => { setCart((prevState) => [...prevState, newItem]); } } 方法时,TypeScript错误出了,如果我将鼠标悬停在setCart上,它将显示:

(prevState)

我该如何解决?

2 个答案:

答案 0 :(得分:0)

在AppContext界面中,该类型设置为从不,因此更改即可更改您期望的类型。

interface AppContext {
  showModal: boolean;
  setShowModal: React.Dispatch<React.SetStateAction<boolean>>;
  cart: Array<Iitem>;
  setCart: React.Dispatch<React.SetStateAction<any[]>>;
  currentSelection: object | null;
  setCurrentSelection: React.Dispatch<React.SetStateAction<null>>;
}

答案 1 :(得分:0)

这似乎可以解决问题

cart: Array<Iitem>;

和....

setCart: React.Dispatch<React.SetStateAction<Array<Iitem>>>;

和....

const [cart, setCart] = useState<Array<Iitem>>([]);