[英]React Context Typescript issue
这是我的 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>
);
};
我的组件.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)
我怎样才能解决这个问题?
在 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>>;
}
这似乎可以解决问题
cart: Array<Iitem>;
和....
setCart: React.Dispatch<React.SetStateAction<Array<Iitem>>>;
和....
const [cart, setCart] = useState<Array<Iitem>>([]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.