代码之家  ›  专栏  ›  技术社区  ›  Megidd

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

  •  1
  • Megidd  · 技术社区  · 2 年前

    我有一个功能,在技术上是一个功能组件:

    export default function Daw() {
      return (
        <>
            <div>Hello world.</div>
        </>
      );
    }
    

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

    我在ReactJS web应用程序中使用这个函数。

    export default function Daw() {
    
      componentDidMount() { // ** Cannot use this ReactJS method!?
      }
    
      return (
        <>
            <div>Hello world.</div>
        </>
      );
    }
    

    问题

    我怎么可能打电话 componentDidMount() 在我的普通函数中使用的方法?有没有一种方法可以做到这一点,而不必将我的函数转换为扩展的类 反应纯组分 ? 可能吗?

    4 回复  |  直到 2 年前
        1
  •  2
  •   Alan Shajan Mattathil    2 年前

    react的第一个导入效果

    import { useEffect } from "react";

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

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

    有关使用useEffect hook学习所有生命周期方法的信息,请参阅react官方文档:- https://reactjs.org/docs/hooks-effect.html

        2
  •  1
  •   Mehdi Namvar    2 年前

    你需要一个钩子!我们在类组件中使用的所有生命周期方法也可以通过React钩子在功能组件中使用,即使是以更好的方式。阅读更多关于React钩子的信息: https://reactjs.org/docs/hooks-intro.html

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

    import { useEffect } from 'react'
    
    export default function Daw() {
      useEffect(() => {
        // Code here will run just like componentDidMount
      }, [])
    
      return (
        <>
            <div>Hello world.</div>
        </>
      )
    }
    

    您还可以通过阅读我的文章了解React中的效果: A Beginner’s Guide to Effects in React

        3
  •  1
  •   Ankit Saxena    2 年前

    你不能使用 componentDidMount() (类生命周期方法)在React功能组件中。可以使用钩子来执行相同的操作。这样地:

    useEffect(() => {
    
    }, []);
    
    

    查看此处了解更多信息- Similar Question

        4
  •  1
  •   Sandeep Gupta    2 年前

    是的,你可以用 useEffect 使用效果 具有以下类方法的能力。即 componentDidMount , componentDidUpdate componentWillUnmoun .

    参考官方文件中的以下信息: https://reactjs.org/docs/hooks-effect.html