当使用usestate作为值时,如何键入React上下文的初始状态
最近,我看到了杰克·赫灵顿(Jack Herrington)的YouTube视频,即“掌握React上下文”,他使用usestate
作为其上下文提供商的价值。这让我很有趣,但是当我尝试使用TypeScript做同样的事情时,我完全因为如何键入初始状态而感到困惑。
示例JS代码:
const CounterContext = createContext(null);
const CounterContextProvider = ({children}) => {
return (
<CounterContext.Provider value={useState(0)}>
{children}
</CounterContext.Provider>
}
使用null
作为默认值不超出问题。我可以为usestate
定义正确的类型,但是初始状态值会是什么样?
I recently saw a youtube video by Jack Herrington, "Mastering React Context" where he used useState
as a value for his context provider. This struck me as interesting but when i tried doing the same with typescript i was stumped completely by how to type the initial state.
Example JS code:
const CounterContext = createContext(null);
const CounterContextProvider = ({children}) => {
return (
<CounterContext.Provider value={useState(0)}>
{children}
</CounterContext.Provider>
}
Using null
as default value is out of the question. I could define the correct types for useState
but what would the initial state values look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
usestate(0)
返回的值是类型的元组[number,dispatch&setStateAction&lt; number
SetStateaction
是从React导入的。因此,使用模拟默认值,看起来像:The value returned by
useState(0)
is a tuple of type[number, Dispatch<SetStateAction<number>>]
, whereDispatch
andSetStateAction
are imported from react. So with a mock default value, that will look like: