我目前正在使用 React 學習 TypeScript,我發現有些內容非常具有挑戰性。我已經創建了 cart.context.tsx 但我不斷收到以下錯誤:
(property) React.ProviderProps<AppContextInterface>.value: AppContextInterface
Type '{ isCartOpen: boolean; setIsCartOpen: React.Dispatch<React.SetStateAction<boolean>>; }' is not assignable to type 'AppContextInterface'.
Types of property 'setIsCartOpen' are incompatible.
Type 'Dispatch<SetStateAction<boolean>>' is not assignable to type '(value: Dispatch<SetStateAction<boolean>>) => boolean'.
Types of parameters 'value' and 'value' are incompatible.
Type 'Dispatch<SetStateAction<boolean>>' is not assignable to type 'SetStateAction<boolean>'.
Type 'Dispatch<SetStateAction<boolean>>' is not assignable to type '(prevState: boolean) => boolean'.
Type 'void' is not assignable to type 'boolean'.ts(2322)
index.d.ts(338, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<AppContextInterface>'
這是我的代碼:
import { createContext, ReactNode, useState } from "react";
interface AppContextInterface {
isCartOpen: boolean;
setIsCartOpen: (value: React.Dispatch<React.SetStateAction<boolean>>) => boolean;
}
export const cartContextDefaultValue: AppContextInterface = {
isCartOpen: false,
setIsCartOpen: () => false
}
export const CartContext = createContext<AppContextInterface>(cartContextDefaultValue);
export const CartProvider = ({ children }: { children: ReactNode }) => {
const [isCartOpen, setIsCartOpen] = useState<boolean>(false);
const value = { isCartOpen, setIsCartOpen }
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
};
錯誤在帶??有 value 屬性的最后一行引發:
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
有人可以看看它并提供幫助嗎?我做錯了什么?
uj5u.com熱心網友回復:
用這個替換你的界面AppContextInterface:
interface AppContextInterface {
isCartOpen: boolean;
setIsCartOpen: Dispatch<SetStateAction<boolean>>;
}
你需要像這樣匯入Dispatch和從反應:SetStateAction
import { createContext, Dispatch, ReactNode, SetStateAction, useState } from "react";
它應該解決問題。
這setIsCartOpen是一個從useState()鉤子回傳的函式,所以它的型別不能是(value: React.Dispatch<React.SetStateAction<boolean>>) => boolean;. 這就是您收到此錯誤的原因。
完整代碼:
import { createContext, Dispatch, ReactNode, SetStateAction, useState } from "react";
interface AppContextInterface {
isCartOpen: boolean;
setIsCartOpen: Dispatch<SetStateAction<boolean>>;
}
export const cartContextDefaultValue: AppContextInterface = {
isCartOpen: false,
setIsCartOpen: () => false
}
export const CartContext = createContext<AppContextInterface>(cartContextDefaultValue);
export const CartProvider = ({ children }: { children: ReactNode }) => {
const [isCartOpen, setIsCartOpen] = useState<boolean>(false);
const value = { isCartOpen, setIsCartOpen }
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448637.html
標籤:javascript 反应 打字稿
上一篇:ReactJS-未定義的變數
下一篇:使用JavaScript合并資料
