在React的官方文档中提到了-

如果你熟悉React类的生命周期方法,你可以思考 将useEffect钩子作为componentDidMount, componentDidUpdate和 componentWillUnmount总和。

我的问题是-我们如何在钩子中使用componentWillMount()生命周期方法?


当前回答

React组件是一个函数?所以只要让componentWillMount moment成为return语句之前的函数体。

function componentWillMountMomentIsHere() {
  console.log('component will mount')
}


function AnyComponent(){
  const [greeting, setGreeting] = useState('Hello')

  componentWillMountMomentIsHere()

  
  return <h1>{greeting}</h1>
}

其他回答

对你最初的问题的简短回答,componentWillMount如何与React Hooks一起使用:

componentWillMount已弃用,被认为是遗留的。反应推荐:

通常,我们建议使用构造函数()来初始化状态。

现在,在Hook FAQ中,你会发现函数组件的类构造函数的等价是:

构造函数:函数组件不需要构造函数。你可以在useState调用中初始化这个状态。如果计算初始状态的开销很大,您可以将一个函数传递给useState。

componentWillMount的用法示例如下所示:

const MyComp = () => {
  const [state, setState] = useState(42) // set initial value directly in useState 
  const [state2, setState2] = useState(createInitVal) // call complex computation

  return <div>{state},{state2}</div>
};

const createInitVal = () => { /* ... complex computation or other logic */ return 42; };

我们最近遇到了这个问题,因为我们需要在组件挂载时做一些事情,也就是我们需要更新全局状态。

所以我创建了这个钩子,不确定这个方法有多好,但到目前为止,只要我们少用它,只用于简单的任务,它就能工作。我可能不会将它用于网络请求和其他长时间运行的复杂任务。

import { useRef } from 'react';

function useComponentWillMount(callback: () => void) {
  const hasMounted = useRef(false);

  if (!hasMounted.current) {
    (() => {
      hasMounted.current = true;
      callback();
    })();
  }

  console.log(hasMounted.current);
  return null;
}

export default useComponentWillMount;

有一个很好的解决方案来实现componentDidMount和componentWillUnmount与useEffect。

根据文档,useEffect可以返回一个“清理”函数。该函数不会在第一次useEffect调用时调用,只在后续调用时调用。

因此,如果我们使用useEffect钩子而没有任何依赖关系,那么该钩子只会在组件挂载时被调用,而“cleanup”函数则会在组件卸载时被调用。

useEffect(() => {
    console.log('componentDidMount');

    return () => {
        console.log('componentWillUnmount');
    };
}, []);

只有在卸载组件时才调用清理返回函数调用。

希望这能有所帮助。

您可以修改useMemo钩子来模仿componentWillMount生命周期事件。 只做:

const Component = () => {
   useMemo(() => {
     // componentWillMount events
   },[]);
   useEffect(() => {
     // componentDidMount events
     return () => {
       // componentWillUnmount events
     }
   }, []);
};

您需要在任何与您的状态交互之前保留useMemo钩子。这不是它的意图,但它适用于我的所有componentWillMount问题。

这是可行的,因为useMemo并不需要实际返回一个值,你也不必实际使用它作为任何东西,但由于它基于依赖关系记住了一个只会运行一次的值(“[]”),并且它位于我们的组件之上,它在组件挂载之前运行一次。

你不能在钩子中使用任何现有的生命周期方法(componentDidMount, componentDidUpdate, componentWillUnmount等)。它们只能在类组件中使用。而Hooks只能用于功能组件。下面这句话来自React文档:

如果你熟悉React类的生命周期方法,你可以把useEffect Hook看作componentDidMount、componentDidUpdate和componentWillUnmount的组合。

建议是,可以在功能组件中从类组件中模拟这些生命周期方法。

componentDidMount中的代码在组件挂载时运行一次。useEffect钩子等价于此行为是

useEffect(() => {
  // Your code here
}, []);

注意这里的第二个参数(空数组)。这将只运行一次。

如果没有第二个参数,useEffect钩子将在组件的每次渲染时被调用,这可能是危险的。

useEffect(() => {
  // Your code here
});

componentWillUnmount用于清理(比如删除事件监听器,取消定时器等)。假设您正在componentDidMount中添加一个事件侦听器,并在componentWillUnmount中删除它,如下所示。

componentDidMount() {
  window.addEventListener('mousemove', () => {})
}

componentWillUnmount() {
  window.removeEventListener('mousemove', () => {})
}

与上述代码等价的钩子如下所示

useEffect(() => {
  window.addEventListener('mousemove', () => {});

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', () => {})
  }
}, [])