React re-write componentWillReceiveProps in useEffect

后端 未结 4 1451
情话喂你
情话喂你 2020-12-18 13:47

So I am re-writing a component with hooks, and I ran into an interesting challenge, I need to mimick some old behaviour of componentWillReceiveProps with the

相关标签:
4条回答
  • 2020-12-18 14:23

    You can create custom hook:

    function usePrevious(value) {
      const ref = useRef();
      useEffect(() => {
        ref.prevLateVal = value;
      });
      return ref.prevLateVal;
    }
    

    and get it used in useEffect()

    const Component = (props) => {
        const currentLateValue = get(`lateMinutes[${bookingId}].value`, props)
        const prevLateVal = usePrevious(currentLateValue);
        useEffect(() => {
            if(prevLateVal !== currentLateValue) {
             // process here
            }
        }, [currentLateValue]) // This will be executed only if currentLateValue changes.
    }
    
    0 讨论(0)
  • 2020-12-18 14:26

    You can use useRef to save the prev props, and use useEffect to run when props change, something like this :

    function MyComponent(props) {
    
      const prevProps = useRef(props);
    
      useEffect(() => {
        const prevLateVal = get(`lateMinutes[${bookingId}].value`, prevProps.current);
        const nextLateVal = get(`lateMinutes[${bookingId}].value`, props);
    
        if (typeof nextLateVal !== 'undefined' && prevLateVal !== nextLateVal) {
          client.connect(bookingId, nextLateVal === null ? 0 : nextLateVal);
        }    
    
        prevProps.current = props;
      }, [props, bookingId]);
    
      return (<div>...</div>)
    }
    
    0 讨论(0)
  • 2020-12-18 14:27

    With the current logic, you want to fire a side-effect only on lateMinutes[${bookingId}].value change:

    const Component = props => {
      useEffect(() => {
        console.log('prop lateMinutes changed');
        // ...
      }, [props[`lateMinutes[${bookingId}].value`]);
      return ...
    };
    
    0 讨论(0)
  • 2020-12-18 14:35

    You don’t need hooks to handle prerender lifecycle. Just put the things in the functional component before returning JSX as the function itself is equivalent to render method of class based component.

    0 讨论(0)
提交回复
热议问题