【问题标题】:How to satisfy typescript when using the context API?使用上下文 API 时如何满足打字稿?
【发布时间】:2021-07-20 16:43:30
【问题描述】:

我目前正在编写我的上下文 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 部分满足 typescript,我可以通过哪两个对象来使 typescript 类型感知而不是抱怨?

【问题讨论】:

  • setIsLogin 实际上是(value: boolean) =&gt; void 类型,所以你可以使用它来代替不太简洁的React.Dispatch&lt;SetStateAction&lt;boolean&gt;&gt;
  • 谢谢你很有用,但没有回答我的问题。

标签: javascript reactjs typescript react-hooks use-context


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    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>
      )
    }
    
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 非常感谢你完美地工作,我尝试给它类型 boolean 等但它没有工作很高兴修复如此简单!
      猜你喜欢
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 2021-09-20
      • 2020-12-19
      • 2019-09-12
      • 2021-03-16
      • 2021-12-18
      • 2012-09-27
      相关资源
      最近更新 更多