我有一个Provider
通过两个提供状态变量及其相应设置器的contexts
.
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>
)
}
通过自定义钩子,我使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'.
由于函数的setteruseState
是我没有创建的函数,所以创建上下文的时候不知道怎么初始化:
const SetBookedBatchContext = createContext(null)
这样 TypeScript 就不会抱怨了。
- 如何知道 setter 函数的初始值?
- 如果我不提供任何类型,如何避免 TS 抱怨 null 值?