简体   繁体   English

在 Visual Studio Code 中使用 useCallback() 获取 Typescript 错误

[英]Getting a Typescript error with useCallback() in Visual Studio Code

I'm new to React hooks, and have run across this code: const multiply = useCallback((value: number) => value * multiplier, [multiplier]);我是 React 钩子的新手,并且遇到过以下代码: const multiply = useCallback((value: number) => value * multiplier, [multiplier]); (from https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d ) (来自https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d

This is confusing to me and Visual Studio Code, which reports this error: Cannot find name 'multiplier'. Did you mean 'multiply'?ts(2552)这让我和 Visual Studio Code 感到困惑,它会报告此错误: Cannot find name 'multiplier'. Did you mean 'multiply'?ts(2552) Cannot find name 'multiplier'. Did you mean 'multiply'?ts(2552)

I feel that I know Typescript reasonably well, but I don't understand [multiplier] or how to resolve this issue.我觉得我知道 Typescript 相当好,但我不明白 [乘数] 或如何解决这个问题。 I suppose it's correct Typescript (it does seem to actually compile).我想它是正确的 Typescript (它似乎确实可以编译)。 Can someone explain to me how this syntax works and how to get Visual Code Studio to accept it?有人可以向我解释这种语法是如何工作的以及如何让 Visual Code Studio 接受它吗? Or if it needs to be fixed?或者是否需要修复?

The full example on that page is this:该页面上的完整示例是这样的:

const multiplier = 2;
// inferred as (value: number) => number
const multiply = useCallback((value: number) => value * multiplier, [multiplier]);

Which compiles just fine. 编译得很好。

multiplier here is just a variable that is defined somewhere.这里的multiplier只是在某处定义的变量。 It could be a constant like the code above or something pulled from component state, or come from an API call.它可以是像上面的代码一样的常量,也可以是从组件 state 中提取的东西,或者来自 API 调用。 There's nothing special about it, it's just a local variable that needs to be defined before you use it.它没有什么特别之处,它只是一个需要在使用之前定义的局部变量。

And [multiplier] just means that multiplier is the only value in an array.[multiplier]只是意味着multiplier是数组中的唯一值。 In this case, the value [2] .在这种情况下,值为[2] It represents the dependencies of the callback.它表示回调的依赖关系。 If any dependencies change, the callback will be recreated.如果任何依赖项发生更改,将重新创建回调。 So there needs to be a way to pass in multiple dependencies.所以需要有一种方法来传递多个依赖项。 In this case, there is only one: multiplier .在这种情况下,只有一个: multiplier So you pass in an array with a single item as [multiplier] .因此,您传入一个包含单个项目的数组作为[multiplier]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM