简体   繁体   中英

converting componentDidUpdate componentDidMount to hooks

Learning react by coding, trying to convert this code into hooks version, but i'm not getting any error and still code is not working ( class version works), just want to have some advice or help if i have converted it in right way or not?

english is not my mother language so could be mistakes.

class:

 componentDidMount() { this.updateCanvas(); const img = this.refs.CameraImage; img.onload = this.updateCanvas.bind(this); } componentDidUpdate(prevProps, prevState, snapshot) { this.updateCanvas(); } componentWillUnmount() { clearInterval(this.snapshotInterval); }

converted version:

 useEffect(() => { updateCanvas(); const img = CameraImage.current; img.onload = updateCanvas; return () => { img.onload = null; }; });

You are right according to React docs about hooks :

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
});

And an example of converted componentWillUnmount to hooks :

useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
});

And code would like this:

useEffect(() => {
    //   componentDidMount run once when the component is mounted
    this.updateCanvas();
    const img = refs.CameraImage;
    img.onload = updateCanvas;      

    // will be called on component unmount 
    return () => {
        clearInterval(this.snapshotInterval);
    }
})

1 - you didn't pass an array into the useEffect Hook , so your component will continuously reload repeatedly.

2 - if you pass an empty array, then you are not watching any variables, and therefore it will only update the state on the first render, exactly like componentDidMount . in your case you are watching snapshot variable so add it as a dependency. So just change your code like this:

useEffect(() => {
    updateCanvas();
    const img = CameraImage.current;
    img.onload = updateCanvas;

    return () => {
      img.onload = null;
    };
  }, [snapshot]);

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