Equivalent to componentDidUpdate using React hooks

前端 未结 4 1367
暗喜
暗喜 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:56

    The useRef creates an "instance variable" in functional component. It acts as a flag to indicate whether it is in mount or update phase without updating state.

    const mounted = useRef();
    useEffect(() => {
      if (!mounted.current) {
        // do componentDidMount logic
        mounted.current = true;
      } else {
        // do componentDidUpdate logic
      }
    });
    

提交回复
热议问题