首页 > 解决方案 > React componentDidMount 不会触发

问题描述

我有一个反应组件,例如带有 componentDidMount 事件的函数。但它根本没有被触发。

function ItemsList() {

    return (
        <div>This is Items List component</div>
    )

    function componentDidMount(  )
    {
        alert('aaaaaaaaaaaaaaaaaaaaaaaaaaaa');
    }
}

有人可以告诉我这种模式有什么问题吗?

标签: javascriptreactjs

解决方案


Functional components do not have lifecycle methods like componentDidMount. You can imitate the lifecycle behaviour of componentDidMount with the useEffect hook:

useEffect(() => {
        alert('aaaaaaaaaaaaaaaaaaaaaaaaaaaa');
}, [])

推荐阅读