我有一个 Provider
它通过两个 contexts
提供了一个状态变量及其对应的 setter .
const BookedBatchContext = createContext({})
const SetBookedBatchContext = createContext(null)
const initialState = {
id: null
}
Provider
看起来像这样:export const BookedBatchProvider = ({ children }: { children: any }) => {
const [bookedBatch, setBookedBatch] = useState(localState ||initialState)
return (
<SetBookedBatchContext.Provider value={setBookedBatch}>
<BookedBatchContext.Provider value={bookedBatch}>
{ children }
</BookedBatchContext.Provider>
</SetBookedBatchContext.Provider>
)
}
通过自定义 Hook ,我制作了
setBookedBatch
可用于其他组件:export const useBookedBatch = () => {
const bookedBatch = useContext(BookedBatchContext)
const setBookedBatch = useContext(SetBookedBatchContext)
return { bookedBatch, setBookedBatch }
}
尝试使用
setBookedBatch
时函数,我在给定组件中出现以下错误:setBookedBatch(selectedBatch)
错误:
TS2721: Cannot invoke an object which is possibly 'null'.
自
useState
的二传手function 是我没有创建的函数,我不知道在创建上下文时如何初始化它:const SetBookedBatchContext = createContext(null)
这样 TypeScript 就不会提示了。
最佳答案
React.createContext
的返回类型和 React.useState
由您传入的初始值的推断确定。
1.) 您可以通过手动指定泛型类型来创建正确的上下文类型:
const SetBookedBatchContext = createContext<null | React.Dispatch<React.SetStateAction<State>>>(null)
注意:
useState
的 setter有类型 React.Dispatch<React.SetStateAction<State>>
,其中 State
随便 localState || initialState
是。2.) 在您的自定义 Hook 中断言
useBookedBatch
,那 setBookedBatch
不是 null
:export const useBookedBatch = () => {
const bookedBatch = useContext(BookedBatchContext)
const setBookedBatch = useContext(SetBookedBatchContext)
if (setBookedBatch === null) throw new Error() // this will make setBookedBatch non-null
return { bookedBatch, setBookedBatch }
// returns: { bookedBatch: {}; setBookedBatch: React.Dispatch<React.SetStateAction<State>>; }
}
3.) 然后
setBookedBatch
稍后可以在没有断言的情况下调用:const App = () => {
const { setBookedBatch } = useBookedBatch()
useEffect(() => { setBookedBatch({ id: "foo" }) }, [])
}
Sample on the playground
关于reactjs - 如何在 createContext 中为 TypeScript 初始化 useState 的 set 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60712598/