react钩子导出函数



我正试图使用ts创建一个自定义钩子,该钩子将返回一个函数,我尝试的方法是:

export const useHook = () => {
const function1 = () => {
logic here
};
const function2=()=>{
logic here
}
return [function1,function2];
};

然后我试着在这样的组件中使用它:

import { useHook } from "./connector/useHook";
function App() {
const {function1,function2} = useHook();
return (
<div>
<Home />
<button onClick={() => function1}>test</button>
<button onClick={() => function2}>test</button>
</div>
);
}
export default App;

然而,我得到了一个错误,说

Property 'function1' does not exist on type '(() => void)[]'. 
const { function1, function2 } = useHook();

{}替换为[],因为您将其作为数组返回:

const [function1, function2] = useHook();

或者从挂钩中返回一个物体:

export const useHook = () => {
const function1 = () => {
// logic here
};
const function2 = () => {
// logic here
};
return {function1, function2};
};

然后您可以将其用作:

cosnt {function1, function2} = useHook();

您已将函数作为数组return [function1,function2];返回。当你使用类似const {function1,function2} = useHook();

因此,有两种方法可以使用

方法1:

从自定义挂钩返回您的函数作为对象:

return { function1, function2 };

像一样使用

const { function1, function2 } = useHook();

方法2:

从自定义挂钩返回数组形式的函数:

return [function1, function2];

像一样使用

const [function1, function2] = useHook();