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?
1 Answer
Reset to default 8The 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
版权声明:本文标题:javascript - When to use constructors in React components? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741985441a2408647.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论