简体   繁体   中英

React JS using useEffect as componentDidMount hook

I am working on a React JS application. I am using functional components and react hooks in my application. I am figuring out the componentDidMount counterpart in hooks.

This is my code

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
  )
}

As you can see in the component, I want to move the function call into componentDidMount counterpart for hooks. How can I do that?

You should simply add an empty array of dependencies to your useEffect call.

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
  )
}

useEffect vs Component life cycle methods

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM