当使用usestate作为值时,如何键入React上下文的初始状态

发布于 2025-01-23 11:49:58 字数 503 浏览 0 评论 0原文

最近,我看到了杰克·赫灵顿(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼泪都笑了 2025-01-30 11:49:58

usestate(0)返回的值是类型的元组[number,dispatch&setStateAction&lt; number SetStateaction是从React导入的。因此,使用模拟默认值,看起来像:

import { createContext, Dispatch, SetStateAction } from "react";

const CounterContext = createContext<
  [number, Dispatch<SetStateAction<number>>]
>([0, () => {}]);

The value returned by useState(0) is a tuple of type [number, Dispatch<SetStateAction<number>>], where Dispatch and SetStateAction are imported from react. So with a mock default value, that will look like:

import { createContext, Dispatch, SetStateAction } from "react";

const CounterContext = createContext<
  [number, Dispatch<SetStateAction<number>>]
>([0, () => {}]);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文