useEffect(() => { // Function to be called when the component mounts const handleEvent = (event) => { console.log('Event occurred:', event); };
// 挂载 Add event listener when the component mounts window.addEventListener('yourEventType', handleEvent);
// 卸载 Clean up the event listener when the component unmounts return() => { window.removeEventListener('yourEventType', handleEvent); }; }, []); // Empty dependency array means this effect runs only once (on mount)
useEffect(() => { // Function to be called at intervals const updateValue = () => { setValue((prevValue) => prevValue + 1); };
// 挂载 Set an interval when the component mounts const intervalId = setInterval(updateValue, 1000); // Replace 1000 with your desired interval in milliseconds
// Clean up the interval when the component unmounts return() => { clearInterval(intervalId); // 卸载 }; }, []); // Empty dependency array means this effect runs only once (on mount)
功能组件从上到下依次运行,一旦功能返回,它就无法继续存活。Functional components run from top to bottom and once the function is returned it can’t be kept alive.
类组件被实例化后,不同的生命周期方法会保持活力,并根据类组件所处的阶段运行和调用。 The class component is instantiated and different life cycle method is kept alive and is run and invoked depending on the phase of the class component.
也被称为无状态组件,因为它们只是接受数据并以某种形式显示出来,主要负责渲染用户界面。Also known as Stateless components as they simply accept data and display them in some form, they are mainly responsible for rendering UI.
也被称为有状态组件,因为它们实现了逻辑和状态。Also known as Stateful components because they implement logic and state.
功能组件中不能使用 React 生命周期方法(例如 componentDidMount)。React lifecycle methods (for example, componentDidMount) cannot be used in functional components.
React 生命周期方法可用于类组件内部(例如 componentDidMount)。React lifecycle methods can be used inside class components (for example, componentDidMount).
Hooks可以很容易地用于功能组件,使其成为有状态的组件。Hooks can be easily used in functional components to make them Stateful. Example: const [name,SetName]= React.useState(' ')
在类组件中实现hook需要不同的语法。It requires different syntax inside a class component to implement hooks. Example: constructor(props) { super(props); this.state = {name: ' '}
不使用构造函数。Constructors are not used.
使用构造函数,因为它需要存储状态。Constructor is used as it needs to store state.