react hooks useEffect() cleanup for only componentWillUnmount?

前端 未结 5 1391
南笙
南笙 2020-12-12 12:32

Let me explain the result of this code for asking my issue easily.

const ForExample = () => {
    const [name, setName] = useState(\'\');
    const [usern         


        
5条回答
  •  攒了一身酷
    2020-12-12 13:04

    instead of creating too many complicated functions and methods what I do is I create an event listener and automatically have mount and unmount done for me without having to worry about doing it manually. Here is an example.

    //componentDidMount
    useEffect( () => {
    
        window.addEventListener("load",  pageLoad);
    
        //component will unmount
        return () => {
           
            window.removeEventListener("load", pageLoad);
        }
    
     });
    

    now that this part is done I just run anything I want from the pageLoad function like this.

    const pageLoad = () =>{
    console.log(I was mounted and unmounted automatically :D)}
    

提交回复
热议问题