【问题标题】:React Context Typescript issue反应上下文打字稿问题
【发布时间】:2020-10-04 03:34:24
【问题描述】:

这是我的 AppContext.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>
  );
};

MyComponent.tsx

const MyComponent = () => {
 const {setCart} =  useContext(AppContext);
 const myFunc = () => {
   setCart((prevState) => [...prevState, newItem]);
 }
}

当我尝试调用 setCart 方法时,TypeScript 出错,如果我将鼠标悬停在 (prevState) 上,它会显示:

(parameter) prevState: never[]
Argument of type '(prevState: never[]) => any[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
  Type '(prevState: never[]) => any[]' is not assignable to type '(prevState: never[]) => never[]'.
    Type 'any[]' is not assignable to type 'never[]'.
      Type 'any' is not assignable to type 'never'.ts(2345)

我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs typescript next.js


    【解决方案1】:

    在 AppContext 接口中,类型设置为 never,因此请更改您期望的类型。

    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>>;
    }
    

    【讨论】:

      【解决方案2】:

      这似乎解决了问题

      cart: Array<Iitem>;
      

      和....

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

      和....

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

      【讨论】:

        猜你喜欢
        • 2020-12-19
        • 2023-03-29
        • 2020-01-29
        • 2023-01-20
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 2021-10-20
        • 2020-01-13
        相关资源
        最近更新 更多