简体   繁体   English

如何用组件生命周期替换 useEffect 钩子?

[英]How to replace useEffect hook with component lifecycle?

I'm forced to use class based component, so how can I replace useEffect with component lifecycle like componentDidMount, componentDidUpdate and componentWillUnmount in my React component.我被迫使用基于类的组件,那么如何在我的 React 组件中用组件生命周期替换useEffect ,如 componentDidMount、componentDidUpdate 和 componentWillUnmount。 Please help请帮忙

const App = () => {
  useEffect(() => {
    store.dispatch(loadUser());
  }, []);

As React team mentioned in this doc正如本文档中提到的 React 团队

Hooks are a new addition in React 16.8. Hooks 是 React 16.8 中的新增功能。 They let you use state and other React features without writing a class.它们让您无需编写类即可使用状态和其他 React 功能。

So if you want to use life cycles you have to use class .所以如果你想使用生命周期,你必须使用class

Use class that extends Component and it must be like this :使用扩展Component类,它必须是这样的:

import React from 'react';

class App extends React.Component {
  //you can use components lifecycle here for example : 

  componentDidMount() {
    store.dispatch(loadUser());
  }
}

After delcaring the constructor you should put the componentDidMount method just ahead, like this:在声明构造函数之后,您应该将 componentDidMount 方法放在前面,如下所示:

class yourComponent extends Component {
   constructor(props){
      // constructor taks...
   }

   componentDidMount() {
      // what you want to do when the component mount
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我们如何在基于 class 的组件的 componentDidUpdate() 生命周期中停止重复调用,就像我们在 useEffect 挂钩中所做的那样? - How can we stop repeated calls in componentDidUpdate() lifecycle of a class based component, like we do in useEffect hook? 将生命周期组件方法重构为 useEffect 钩子有哪些技巧? - What are some tips on refactoring lifecycle component methods into useEffect hook? 如何在 useEffect Hook 中重新渲染组件 - How to rerender component in useEffect Hook React 'useEffect' hook 替换了多少生命周期方法? - React 'useEffect' hook replaces how many lifecycle methods? 如何使用 useEffect 钩子渲染加载组件? - How to render a loading component with the useEffect hook? 如何将 useEffect 从组件移动到自定义挂钩 - How to move useEffect from component to custom hook 生命周期方法和useEffect挂钩之间有什么区别? - What is difference between lifecycle method and useEffect hook? 从 componentDidUpdate 生命周期方法重写 useEffect 钩子 - Rewrite useEffect hook from componentDidUpdate lifecycle method 如何在'useEffect'钩子中获取最新的组件变量值? - How to get latest component variable value in 'useEffect' hook? 如何在组件卸载上使用 useEffect 钩子来有条件地运行代码 - how to use the useEffect hook on component unmount to conditionally run code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM