React re-write componentWillReceiveProps in useEffect

后端 未结 4 1468
情话喂你
情话喂你 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.
    }
    

提交回复
热议问题