【发布时间】: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) => void类型,所以你可以使用它来代替不太简洁的React.Dispatch<SetStateAction<boolean>> -
谢谢你很有用,但没有回答我的问题。
标签: javascript reactjs typescript react-hooks use-context