reactjs - 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 对应的钩子中。我怎样才能做到这一点?
解决方案
您应该简单地将一个空的依赖项数组添加到您的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
)
}
推荐阅读
- python - UserWarning:此图包含与tight_layout 不兼容的轴,因此结果可能不正确。在 plt.show 之后
- java - QueryDsl 反转多对多连接
- javascript - useState() Hook 在 reacts.js 中是如何工作的?
- javascript - 承诺没有按预期执行
- jquery - 在取消选中复选框时淡出相应的图像
- html - 如何调整图像大小以保持比例
- vb.net - OpenFileDialog - png 文件不显示在对话框中
- c++ - Leetcode 问题运行时错误:引用绑定到“struct value_type”类型的空指针(stl_vector.h)
- python - 如何将熊猫数据框写入csv文件?如何从最终字典中删除列表数组大括号([])?
- python - Python乘法相当于整数除法