Equivalent to componentDidUpdate using React hooks

前端 未结 4 1369
暗喜
暗喜 2020-12-13 06:10

tldr; How do I simulate componentDidUpdate or otherwise use the key prop with an array to force my component to be reset?

4条回答
  •  悲哀的现实
    2020-12-13 06:49

    use a custom hook

    export const useComponentDidUpdate = (effect, dependencies) => {
      const hasMounted = useRef(false);
    
      useEffect(
        () => {
          if (!hasMounted.current) {
            hasMounted.current = true;
            return;
          }
          effect();
        }, 
        dependencies
      );
    };
    
    

    Effect will not run after the initial render. Thereafter, it depends on the array of values that should be observed. If it's empty, it will run after every render. Otherwise, it will run when one of it's values has changed.

提交回复
热议问题