简体   繁体   中英

React lifecycle methods to hooks

I have simple blog with articles. And I want to rewrite classes to functional components and hooks. Now I got this logic in lifecycle methods for my page with edit/add form: it works fine.

componentDidUpdate(prevProps, prevState) {
 if (this.props.match.params.id !== prevProps.match.params.id) {
    if (prevProps.match.params.id) {
        this.props.onUnload();
      }

      this.id = this.props.match.params.id;
        if (this.id) {
            return this.props.onLoad(userService.articles.get(this.id));
        }
        this.props.onLoad(null);
   }
   this.isLoading = false;
}

componentDidMount() {
  if (this.id) {
    this.isLoading = true;
    return this.props.onLoad(userService.articles.get(this.id));
  }
  this.isLoading = false;
  this.props.onLoad(null);
}
   
componentWillUnmount() {
   this.props.onUnload();
}
   
shouldComponentUpdate(newProps, newState) {
   if (this.props.match.params.id !== newProps.match.params.id) {
      this.isLoading = true;
   }
   return true;
}

I rewrote it all to hooks like that:

//componentDidMount
  useEffect(() => {
    if (id) {
      setIsloading(true);
      return props.onLoad(userService.articles.get(id));
    }
    setIsloading(false);
    props.onLoad(null);
  }, []);

  useEffect(()=> {
      prevId.current = id;
      }, [id]
  );

  //componentDidUpdate
  useEffect(() => {
    //const id = props.match.params.id;
    if (id !== prevId.current) {
      if (prevId.current) {
        props.onUnload();
      }
      if (id) {
        return props.onLoad(userService.articles.get(id));
      }
      props.onLoad(null);
    }
    setIsloading(false);
  });

  //componentWillUnmount
  useEffect(() => {
     return props.onUnload();
  }, []);

  1. I got error - "Too many re-renders." at codesandbox full code: codesandbox

Its strange, but at localhost there is no error "Too many re-renders."

  1. Don't know what to do with my class "shouldComponentUpdate" method how to rewrite it to hooks. Tryed 'memo' but have no idea how to write in in this case.

  2. And anyway I'm missing something, because it all won't work - it's not updating form fields properly.

If you have a good knowledge with react hooks please help, or give some advice - how to fix it?

The effect without dependency is causing "Too many re-renders." : it runs after every render then it calls setIsLoading to update the state( loading ) which will cause the component to re-render, which will run the effect again and the setState will be called again and effect and so on...

//componentDidUpdate
  useEffect(() => {
    //const id = props.match.params.id;
    if (id !== prevId.current) {
      if (prevId.current) {
        props.onUnload();
      }
      if (id) {
        return props.onLoad(userService.articles.get(id));
      }
      props.onLoad(null);
    }
    setIsloading(false);
  })

to fix the issue either remove the setIsLoading from it, or add IsLoading as dependency.

//componentDidUpdate
  useEffect(() => {
    ...
    setIsloading(false);
  },[isLoading]);

you can also merge two mount effects into one like this ( yours is also working, but I think this is stylistically preferable):

//componentDidMount
  useEffect(() => {
    if (id) {
      setIsloading(true);
      return props.onLoad(userService.articles.get(id));
    }
    setIsloading(false);
    props.onLoad(null);

    //componentWillUnmount
    return function () {
      props.onUnload()
    }
  }, []);

for the second bullet: about rewriting your component's shouldComponentUpdate ; first I must point that your existing shouldComponentUpdate isn't sound reasonable, since you always return true , and you are only using it to trigger loading state; and its not eligible to be written with React.memo (which is ~equivalent of shouldComponentUpdate in class components); so you only need something to be executed on every props change to determine loading state and for that you can use an effect with props as its dependency like this:

//manually keeping old props id
const prevPropsId = useRef();

useEffect(() => {
   if (prevPropsId.current !== props.match.params.id) {
      setIsLoading(true);
   }
   prevPropsId.current = props.match.params.id;
 }, [props.match.params.id]);
// this hook only run if `props.match.params.id` change 

based on my realization this shall do the job, ( despite having hard time understanding why you write the logic this way in the first place) and if it's not doing fine you may tune the logic a little bit to match your needs, you get the idea how the props change effect works. also you many need to handle typeError in case id , params or match doesn't exist and Optional chaining can be handy tool here -> props.match?.params?.id

If you miss the old lifecycle hooks, you could always recreate them as custom hooks:

function useComponentDidMount(effect) {
  useEffect(() => {
    effect();
  }, []);
}
function useComponentWillUnmount(effect) {
  useEffect(() => {
    return effect;
  }, []);
}
function useComponentDidUpdate(effect, dependencies) {
  const hasMountedRef = useRef(false);
  const prevDependenciesRef = useRef(null)
  useEffect(() => {
    // don't run on first render, only on subsequent changes
    if (!hasMountedRef.current) {
      hasMountedRef.current = true;
      prevDependenciesRef.current = dependencies;
      return;
    }
    // run effect with previous dependencies, like in componentDidUpdate!
    effect(...prevDependenciesRef.current || []);
    prevDependenciesRef.current = dependencies;
  }, dependencies)
}

Usage (your example refactored):

  //componentDidMount
  useComponentDidMount(() => {
    if (id) {
      setIsloading(true);
      props.onLoad(userService.articles.get(id));
      return;
    }
    setIsloading(false);
    props.onLoad(null);
  });

  //componentDidUpdate
  useComponentDidUpdate((prevId) => {
    if (prevId) {
      props.onUnload();
    }
    if (id) {
      props.onLoad(userService.articles.get(id));
      return;
    }
    props.onLoad(null);
    setIsloading(false);
  }, [id]);

  //componentWillUnmount
  useComponentWillUnmount(() => {
     props.onUnload();
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM