作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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>
)
}
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)
最佳答案
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
是。
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>>; }
}
setBookedBatch
稍后可以在没有断言的情况下调用:
const App = () => {
const { setBookedBatch } = useBookedBatch()
useEffect(() => { setBookedBatch({ id: "foo" }) }, [])
}
关于reactjs - 如何在 createContext 中为 TypeScript 初始化 useState 的 set 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60712598/
我是一名优秀的程序员,十分优秀!