在下面的代码中,我收到TypeScript错误:
This expression is not callable. Type 'typeof React' has no call signatures TS2349
我需要以什么方式声明类型?感谢帮助,因为我习惯了 React 中的 TypeScript。
useEffect(() => {
// subscribe to some data source
console.log('subscribe to some data source');
return () => {
// unsubscribe to avoid memory leak
console.log('this will run when the component unmounts');
};
});
useEffect不是从react默认导出。
您需要导入,因为不是默认导出,如下所示:
import {useEffect} from 'react';
因为我导入了 React 如下
import * as React from "react";
我需要在 useEffect 钩子前面加上 React 如下:
React.useEffect(() => {
-
useEffect
钩子应该在功能组件的主体内部调用。不能在组件声明之外直接调用它。 -
此外,请确保从库中导入 useEffect
'react'
:
import React, { useEffect } from 'react';
下面的示例代码应按预期工作:
import React, { useEffect } from 'react';
const YourComponent: React.FC = () => {
useEffect(() => {
// This function will run when the component mounts
// Perform some side effects or subscribe to a data source
console.log('Subscribe to some data source');
return () => {
// This function will run when the component unmounts
// Cleanup or unsubscribe to avoid memory leaks
console.log('This will run when the component unmounts');
};
}, []);
return (
// JSX for your component
<div>Component content</div>
);
};
export default YourComponent;