js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

如何用 Hooks 模拟 componentDidMount 与componentWillUnmount

Open Sunny-117 opened this issue 3 years ago • 1 comments

Sunny-117 avatar Nov 03 '22 09:11 Sunny-117

function MyComponent() {
  useEffect(() => {
    // 这里的代码会在组件挂载后执行,模拟componentDidMount的行为
    console.log('Component did mount');

    // 返回一个函数,在组件卸载之前执行,模拟componentWillUnmount的行为
    return () => {
      console.log('Component will unmount');
    };
  }, []); // 传递一个空数组[]表示这个effect不依赖于props或state中的任何值,因此只运行一次

  return (
    <div>Hello, World!</div>
  );
}

floatGray avatar Apr 11 '24 02:04 floatGray