问题描述
我总是编写React代码,特别是在ES6类中。但我的问题是,我们什么时候在React Components中使用构造函数(props)
? 构造函数(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 component together with its props?
推荐答案
中解释的那样,React组件的构造函数在第一次组装或实例化时执行。在后续渲染中永远不会再调用它。
the constructor of a React component is executed once the first time the component is mounted, or instantiated. It is never called again in subsequent renders.
通常,构造函数用于设置组件的内部状态
,例如:
Typically the constructor is used to set-up a component'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
}
}
构造函数不直接指示渲染的内容b ya component。
The constructor does not directly dictate what is rendered by a component.
组件呈现的内容由其 render
方法的返回值定义。
What is rendered by a component is defined by the return value of its render
method.
这篇关于何时在React组件中使用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!