简体   繁体   中英

React Context Typescript issue

This is my 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]);
 }
}

When I try to call the setCart method, TypeScript errors out and if I hover over (prevState) it shows:

(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)

How can I fix this?

In AppContext interface the type is set to never so change change the type that you expect to be there.

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

This appears to solve the issue

cart: Array<Iitem>;

and....

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

and....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM