[英]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.