React/TypeScript - “Dispatch>”的作用是什么代表?

发布于 2025-01-11 04:44:18 字数 254 浏览 0 评论 0 原文

我正在用 TypeScript 编写 React 组件的前端测试。由于代码来自更有经验的程序员,因此某些数据类型对我来说似乎有点新。现在我有了一个用“Dispatch”定义的道具作为数据类型。我注意到使用 useState-Hook 的 set-property 是有效的,但我不太确定这是否是应该使用 prop 的方式。供参考:该道具称为“onFullScreenClick”。我将非常感谢您对最有可能放入的内容进行解释和示例

I am writing Frontend Tests for React Components in TypeScript. Since the Code is from a more experienced Programmer, some Datatypes seem a bit new for me. Now I've got a prop that is defined with "Dispatch<SetStateAction>" as datatype. I've noticed that using the set-property of a useState-Hook is working, but I'm not really sure if this is how the prop is supposed to be used. For reference: The prop is called "onFullScreenClick". I'd be very grateful for an explanation and an example for what's most likely to be put in

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

煞人兵器 2025-01-18 04:44:19

如果您查看类型的来源:

type SetStateAction<S> = S | (prevState: S) => S;

type Dispatch<A> = (action: A) => void;

Dispatch 将操作作为参数并返回任何有意义的内容 (void)。
操作有多种类型,SetStateAction 就是其中之一。

请记住,useState 可以采用新状态,或者采用先前状态并返回新状态的函数。

所以 useState 的类型实际上是:

type UseState<S> = (action: S | ((prevState: S) => S)) => void;

If you look at the source of the typings:

type SetStateAction<S> = S | (prevState: S) => S;

type Dispatch<A> = (action: A) => void;

Dispatch takes an action as a parameter and returns nothing meaningful (void).
There are multiple types of actions, and one of them is SetStateAction.

Remember that useState can take a new state, or a function that takes the previous state and returns the new state.

So useState's type is actually:

type UseState<S> = (action: S | ((prevState: S) => S)) => void;
我爱人 2025-01-18 04:44:19

这只是告诉打字稿的一种方式,我们传入的道具的类型

看看这个简单的计数器 来自沙箱的示例

我们在父级中有 const [num, setnum] = useState(0),并且我们将状态和 setter 函数传递给子级component

num 的类型是从 useState(0) 推断出来的,如果我们想要 setter 函数的类型,我们只需将鼠标悬停在它上面,我们就会得到

const setNum: Dispatch>

而这个 Dispatch> 是 setter 函数的类型。

It's just a way telling typescript, the type of the props we are passing in

Take a look at this simply counter example from sandbox

We have const [num, setnum] = useState(0) in the parent, and we pass both state and setter function to child component

The type of the num is infered from useState(0), if we want the type of the setter function, we just hover mouse over it, and we get

const setNum: Dispatch<SetStateAction<number>>

and this Dispatch<SetStateAction<number>> is the type of setter function.

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