When is it appropriate to use a constructor in REACT?

ⅰ亾dé卋堺 提交于 2019-12-03 17:03:24

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Typically, in React constructors are only used for two purposes:

  • Initializing local state by assigning an object to this.state.
  • Binding event handler methods to an instance.

https://reactjs.org/docs/react-component.html#constructor

Linke in your example, it's useful use constructor when you need to initialize your state, or bind some event-listener-function

  1. <element onClick={this.handler} />
  2. this.handler = this.bind.handler(this); inside the constructor
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!