React 功能组件:如何使用 componentDidMount()

use*_*291 11 javascript reactjs

我有一个函数,从技术上讲,它是一个 React 函数组件:

export default function Daw() {
  return (
    <>
        <div>Hello world.</div>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

当然,我的普通函数不可能有ReactJS的方法componentDidMount()。因为它不是一个扩展的类React.PureComponent

我在 ReactJS Web 应用程序中使用此函数。

export default function Daw() {

  componentDidMount() { // ** Cannot use this ReactJS method!?
  }

  return (
    <>
        <div>Hello world.</div>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

问题

我怎样才能componentDidMount()在我的普通函数中调用ReactJS的方法?有没有办法做到这一点,而不将我的函数转换为扩展的类React.PureComponent?是否可以?

Ala*_*hil 12

首先从react导入useEffect

import { useEffect } from "react";

然后使用 useEffect 和一个空的依赖数组,它与 componentDidMount() 相同

useEffect(() => { console.log("Mounted"); },[]);

请参阅 React 官方文档,了解使用 useEffect hook 的所有生命周期方法:- https://reactjs.org/docs/hooks-effect.html


Meh*_*var 10

你将需要 React Hooks!我们在类组件中执行的所有生命周期方法也可以通过 React Hooks 在功能组件中使用,甚至以更好的方式。在这里阅读有关 React hooks 的更多信息:https ://reactjs.org/docs/hooks-intro.html

\n

在这种情况下,componentDidMount 的等价物是这样的:

\n
import { useEffect } from \'react\'\n\nexport default function Daw() {\n  useEffect(() => {\n    // Code here will run just like componentDidMount\n  }, [])\n\n  return (\n    <>\n        <div>Hello world.</div>\n    </>\n  )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

您还可以通过阅读我的文章来了解 React 中的效果:A Beginner\xe2\x80\x99s Guide to Effects in React

\n