首页 > 解决方案 > React JS 使用 useEffect 作为 componentDidMount 钩子

问题描述

我正在开发一个 React JS 应用程序。我在我的应用程序中使用功能组件和反应钩子。我正在找出钩子中的 componentDidMount 对应项。

这是我的代码

const Items = () => {
   useEffect(() => {
    fetchItems(); //this function is being called whenever the state is updated. I am looking for componentDidMount counterpart
    return () => {
      //clean up
    }
  })

  return (
     //return the view component
  )
}

正如您在组件中看到的那样,我想将函数调用移动到 componentDidMount 对应的钩子中。我怎样才能做到这一点?

标签: reactjsreact-hooksuse-effect

解决方案


您应该简单地将一个空的依赖项数组添加到您的useEffect调用中。

const Items = () => {
   useEffect(() => {
    fetchItems(); //this function is being called whenever the state is updated. I am looking for componentDidMount counterpart
    return () => {
      //clean up
    }
  }, []) // <-- add this

  return (
     //return the view component
  )
}

推荐阅读