componentWillReceiveProps, componentDidUpdate for React Hook

后端 未结 8 1206
闹比i
闹比i 2020-12-25 11:00

I run into two challenges:

  • Even if, as per React guideline, derived state is discouraged, but some edge cases still need it.
    In terms of
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-25 11:25

    The react hook equivalent to the old componentWillReceive props can be done using the useEffect hook, just specifying the prop that we want to listen for changes in the dependency array.

    I.e:

    export default (props) => {
    
        useEffect( () => {
            console.log('counter updated');
        }, [props.counter])
    
        return 
    Hi {props.counter}
    }

    For componentDidUpdate just by omitting the dependency array, the useEffect function will be called after every re-render.

    I.e:

    export default (props) => {
    
        useEffect( () => {
            console.log('counter updated');
        })
    
        return 
    Hi {props.counter}
    }

提交回复
热议问题