[英]How to specify a function as an optional parameter to a hook with a default value
I am trying to write a custom hook in a react app using TypeScript that can take several, optional callback functions.我正在尝试使用 TypeScript 在 React 应用程序中编写一个自定义钩子,该钩子可以采用多个可选的回调函数。 However I am getting the following error:但是我收到以下错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'onUpdate').未捕获的类型错误:无法读取未定义的属性(读取“onUpdate”)。 I write an interface like this:我写了一个这样的界面:
interface UseMyHookProps {
onConnect:() => void;
onUpdate?:() => void;
onDisconnect?:() => {};
}
And then my hook like this:然后我的钩子是这样的:
const useMyHook = ({ onConnect = () => {}, onUpdate = () => {}, onDisconnect = () => {} }: UseMyHookProps) => {
...
// call the callback if defined.
onUpdate();
};
finally I call the hook in a component function like this:最后,我在组件函数中调用钩子,如下所示:
const MyComponent = () => {
useMyHook();
...
};
I don't understand why I get this error.我不明白为什么我会收到这个错误。 I say the callback is optional and provide a default argument of a void function that does nothing.我说回调是可选的,并提供一个不做任何事情的 void 函数的默认参数。
The problem is that you are providing default values only for the attributes of the object, but not for the object itself which can still be undefined
if you call the hook without parameters.问题是你只为对象的属性提供默认值,而不是为对象本身提供默认值,如果你调用不带参数的钩子,它仍然可以是undefined
。
You can easily solve that by defaulting the hook's parameter to an empty object = {}
您可以通过将钩子的参数默认为空对象来轻松解决这个问题= {}
const useMyHook = ({
onConnect = () => {},
onUpdate = () => {},
onDisconnect = () => {},
}: UseMyHookProps = {}) => { // <<<<
// call the callback if defined.
onUpdate();
};
The version below is exatcly the same thing but more verbose, you can see that without defaulting params = {}
, params
would be undefined and the object destructuring below would fail下面的版本完全相同,但更冗长,你可以看到如果没有默认params = {}
, params
将是未定义的,并且下面的对象解构将失败
const useMyHook = (params: UseMyHookProps = {}) => {
const {
onConnect = () => {},
onUpdate = () => {},
onDisconnect = () => {},
} = params
// call the callback if defined.
onUpdate();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.