admin管理员组

文章数量:1316006

I always write React code, particularly in ES6 Classes. But my question is, when do we use constructor(props) in React Components? Does the constructor(props) line has something to do with the rendering of the ponent together with its props?

I always write React code, particularly in ES6 Classes. But my question is, when do we use constructor(props) in React Components? Does the constructor(props) line has something to do with the rendering of the ponent together with its props?

Share Improve this question edited Mar 1, 2017 at 10:06 sdgluck 27.3k12 gold badges81 silver badges95 bronze badges asked Aug 2, 2016 at 5:40 CyvalCyval 2,5194 gold badges18 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

The accepted answer is incorrect (perhaps just a misuse of the word "render").

As I explain in my ment on it the constructor of a React ponent is executed once the first time the ponent is mounted, or instantiated. It is never called again in subsequent renders.

Typically the constructor is used to set-up a ponent's internal state, for example:

constructor () {
  super()
  this.state = {
    // internal state
  }
}

Or if you have the class property syntax available (e.g. via Babel) you can forgo declaring a constructor if all you are using it for is to initialise the state:

class Example extends React.Component {
  state = {
    // internal state
  }
}

Does the constructor(props) line has something to do with the rendering of the ponent together with its props?

The constructor does not directly dictate what is rendered by a ponent.

What is rendered by a ponent is defined by the return value of its render method.

本文标签: javascriptWhen to use constructors in React componentsStack Overflow