使用上下文API时如何满足打字稿?

How to satisfy typescript when using the context API?

我目前正在这样写我的上下文 API:

import React, { useState, createContext, SetStateAction } from 'react'

type LoginContextProps = [boolean, React.Dispatch<SetStateAction<boolean>>]

export const LoginContext = createContext<LoginContextProps>([])

export const LoginProvider = ({
  children,
}: React.PropsWithChildren<unknown>) => {
  const [isLogin, setIsLogin] = useState(false)
  return (
    <LoginContext.Provider value={[isLogin, setIsLogin]}>
      {children}
    </LoginContext.Provider>
  )
}

但是我不确定如何在代码的 createContext 部分满足打字稿,我可以传递哪两个对象来使打字稿类型感知而不是抱怨?

您需要提供一个有效的默认上下文,它应该满足类型LoginContextProps。例如,它可能是 [false, () => {}]。您使用的 [] 不是有效值,因为它是空的,但是恰好在任何 LoginContext.Provider 之外的每个组件都期望 LoginContext 会为它们提供一个布尔值和一个布尔值 setter.

import React, { useState, createContext, SetStateAction } from 'react'

type LoginContextProps = [boolean, React.Dispatch<SetStateAction<boolean>>]
type LoginProviderProps = {
   children: React.ReactNode
}
export const LoginContext = createContext<LoginContextProps>([])

export const LoginProvider = ({
  children,
}: LoginProviderProps) => {
  const [isLogin, setIsLogin] = useState<boolean>(false)

  const  values: LoginContextProps = [isLogin, setIsLogin]

  return (
    <LoginContext.Provider value={values}>
      {children}
    </LoginContext.Provider>
  )
}

您可以简单地将它们设为可选:

type LoginContextProps = {
  isLogin?: boolean, 
  setIsLogin?: React.Dispatch<SetStateAction<boolean>>
}