When is it appropriate to use a constructor in REACT?

前端 未结 3 1866
长发绾君心
长发绾君心 2020-12-01 17:08

I understand the concept of constructors in OOP languages like C++. However, I am not entirely sure when to use a constructor in REACT. I do understand that JavaScript is ob

3条回答
  •  情话喂你
    2020-12-01 17:53

    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

提交回复
热议问题