代码之家  ›  专栏  ›  技术社区  ›  ProEvilz

反应上下文类型脚本问题

  •  0
  • ProEvilz  · 技术社区  · 5 年前

    这是我的应用程序上下文。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>
      );
    };
    

    我的成分。tsx

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

    当我试着打电话给 setCart 方法,键入脚本出错,如果我将鼠标悬停在 (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)
    

    我该怎么解决这个问题?

    2 回复  |  直到 5 年前
        1
  •  0
  •   niles87    5 年前

    在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>>;
    }
    
        2
  •  0
  •   ProEvilz    5 年前

    这似乎解决了这个问题

    cart: Array<Iitem>;
    

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

    const [cart, setCart] = useState<Array<Iitem>>([]);
    
    推荐文章