React useEffect cleanup with current props

前端 未结 3 1487
野趣味
野趣味 2021-01-18 02:21

I ran into a need of cleaning a useEffect when component is unmounted but with an access to the current props. Like componentWillUnmount can do by getting this.props.whateve

3条回答
  •  春和景丽
    2021-01-18 02:43

    Was referenced to this question from another one so will do a bit of grave digging for it since there is no accepted answer.

    The behaviour you want can never happen because B never renders with a count value of 5, component A will not render component B when count is 5 because it'll render unmounted instead of B, the last value B is rendered with will be 4.

    If you want B to log the last value it had for count when it unmounts you can do the following:

    Note that effects executes after all components have rendered

    const useIsMounted = () => {
      const isMounted = React.useRef(false);
      React.useEffect(() => {
        isMounted.current = true;
        return () => (isMounted.current = false);
      }, []);
      return isMounted;
    };
    const B = ({ count }) => {
      const mounted = useIsMounted();
      React.useEffect(() => {
        // eslint-disable-next-line react-hooks/exhaustive-deps
        return () => !mounted.current && console.log(count);
      }, [count, mounted]);
    
      return 
    {count}
    ; }; const A = () => { const [count, setCount] = React.useState(0); const handleClick = React.useCallback(() => { setCount(prevCount => prevCount + 1); }, []); if (count === 5) { //B will never be rendered with 5 return
    Unmounted
    ; } return ( ); }; ReactDOM.render(, document.getElementById('root'));
    
    
    

提交回复
热议问题