我正在研究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
)
}
正如您在组件中看到的那样,我想将函数调用移到与hook对应的componentDidMount对应对象中。我该怎么办?
答案 0 :(得分:2)
您只需在您的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
)
}
答案 1 :(得分:2)
useEffect与组件生命周期方法
const [data, setData]=useState("")
const [inpVal, setInpVal]= useState("")
useEffect(() => {
fetchItems(inpVal);
},[]); //if you put an empty array then it will act as componentdidmount
useEffect(() => {
fetchItems(inpVal);
},[inpVal]); //if you put an inpVal in array then it will act as componentDidUpdate which means when ever the inpVal change useeffect will run