React+TypeScript全局上下文报错:Type 'string'无法分配给SetStateAction<null>
问题解决:Type 'string' is not assignable to type 'SetStateAction'
问题原因
你声明sendURLToEtsy状态时用了useState(null),TypeScript会自动推断该状态类型为null,对应的setSendURLToEtsy只能接受null类型的更新值。但你的globalState接口要求setSendURLToEtsy是React.Dispatch<React.SetStateAction<null | string>>(可接受string或null),两者类型不匹配导致报错。
解决方案
给useState显式指定状态类型为string | null,让TypeScript明确该状态支持字符串或null类型,对应的setter函数类型会自动匹配接口要求。
修改后的代码
"use client"; import { createContext, useContext, useState } from 'react'; interface globalState { isLoading: boolean; isError: boolean; errorMessage: string | null; sendURLToEtsy: string | null; setIsError: React.Dispatch<React.SetStateAction<boolean>>; setIsLoading: React.Dispatch<React.SetStateAction<boolean>>; setErrorMessage: React.Dispatch<React.SetStateAction<string>>; setSendURLToEtsy: React.Dispatch<React.SetStateAction<null | string>>; } export const globalContext = createContext<globalState>({ isLoading: false, isError: false, errorMessage: "Default Error Message Context", sendURLToEtsy: null, setIsError: () => {}, setIsLoading: () => {}, setErrorMessage: () => {}, setSendURLToEtsy: () => {}, }); export default function GlobalContextProvider({children}: {children: React.ReactNode;}) { const [isError, setIsError] = useState(false) const [isLoading, setIsLoading] = useState(false) const [errorMessage, setErrorMessage] = useState("Default Error Message Context") // 显式指定状态类型为 string | null const [sendURLToEtsy, setSendURLToEtsy] = useState<string | null>(null) return <globalContext.Provider value={{ isLoading, isError, errorMessage, sendURLToEtsy, setSendURLToEtsy, setIsError, setIsLoading, setErrorMessage, }}> {children} </globalContext.Provider> } export const useGlobalContext = () => useContext(globalContext);
内容的提问来源于stack exchange,提问作者Q-man
相关产品推荐
相关产品推荐

