如何在 React Hooks 中使用 componentWillMount()? [英] How to use componentWillMount() in React Hooks?

查看:121
本文介绍了如何在 React Hooks 中使用 componentWillMount()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 的官方文档中提到 -

In the official docs of React it mentions -

如果你熟悉 React 类的生命周期方法,你可以认为useEffect Hook 作为 componentDidMount、componentDidUpdate 和componentWillUnmount 合并.

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

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

My question is - how can we use the componentWillMount() lifecyle method in a hook?

推荐答案

您不能使用任何现有的生命周期方法(componentDidMountcomponentDidUpdatecomponentWillUnmount 等)在一个钩子中.它们只能在类组件中使用.使用 Hooks,您只能在功能组件中使用.下面这行来自 React 文档:

You cannot use any of the existing lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount etc.) in a hook. They can only be used in class components. And with Hooks you can only use in functional components. The line below comes from the React doc:

如果你熟悉 React 类的生命周期方法,你可以把 useEffect Hook 想成 componentDidMountcomponentDidUpdatecomponentWillUnmount 合并.

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

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

suggest is, you can mimic these lifecycle method from class component in a functional components.

componentDidMount 中的代码在安装组件时运行一次.useEffect 与此行为等效的钩子是

Code inside componentDidMount run once when the component is mounted. useEffect hook equivalent for this behaviour is

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

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

Notice the second parameter here (empty array). This will run only once.

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

Without the second parameter the useEffect hook will be called on every render of the component which can be dangerous.

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

componentWillUnmount 用于清理(如删除事件侦听器、取消计时器等).假设您要在 componentDidMount 中添加一个事件侦听器,并在 componentWillUnmount 中删除它,如下所示.

componentWillUnmount is use for cleanup (like removing event listeners, cancel the timer etc). Say you are adding a event listener in componentDidMount and removing it in componentWillUnmount as below.

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

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

Hook 相当于上面的代码如下

Hook equivalent of above code will be as follows

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

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

这篇关于如何在 React Hooks 中使用 componentWillMount()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆