React constructor() Method

React 组件生命周期React Component Lifecycle

The format of the constructor() method is as follows:

constructor(props)

Before a React component is mounted, its constructor() will be called.

When implementing a constructor for a React.Component subclass, you should call super(props) before any other statements.

In the following example, React calls the constructor every time a component is created:

Example

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritewebsite: "example"}; } render() { return ( <h1>My favorite websites{this.state.favoritewebsite}</h1> ); } }

Try it Yourself »

In React, the constructor is only used for the following two cases:

  • Initializing internal state by assigning an object to this.state.
  • Binding an instance to event handler functions.

If you don't initialize state or bind methods, you don't need to implement a constructor for the React component.

Do not call setState() in the constructor() function. If your component needs to use internal state, directly assign the initial state to this.state in the constructor:

constructor(props) {
  super(props);
  // 不要在这里调用 this.setState()
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}

You can only assign this.state directly in the constructor. To assign it in other methods, you should use this.setState() instead.

React 组件生命周期React Component Lifecycle

Other Extensions