什么时候在REACT中使用构造函数合适? [英] When is it appropriate to use a constructor in REACT?

查看:95
本文介绍了什么时候在REACT中使用构造函数合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解OOP语言(例如C ++)中的构造函数的概念。但是,我不完全确定何时在REACT中使用构造函数。我确实知道JavaScript是面向对象的,但是我不确定构造函数实际上是在构造。

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 object oriented, but I am not sure what the constructor is actually 'constructing'.

在渲染子组件时,是否需要在子组件?例如:

When rendering a child component, do you need a constructor in the child component? For example:

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         items: [],
         error: null
      }
    }
    render () {
       return (
          <React.Fragment>
             <ChildComponent data={this.state.items}></ChildComponent>
          </React.Fragment>
       )
    }
}

为了简洁起见,我将简短示例。但是,为什么需要构造函数?

I will keep the example short for the sake of brevity. But, why would do you need a constructor? And would you need a constructor in the child component for props?

很有可能我的ES6知识还不够。

It is possible that my ES6 knowledge is not up to snuff.

推荐答案

如果您不初始化状态并且不绑定方法,则无需为React组件实现构造函数。

React组件的构造函数在挂载之前被调用。为React.Component子类实现构造函数时,应在其他任何语句之前调用super(props)。否则,在构造函数中将无法定义this.props,这可能会导致错误。

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.

通常,在React构造器中仅用于两个目的:

Typically, in React constructors are only used for two purposes:


  • 通过向this.state分配对象来初始化本地状态。

  • 将事件处理程序方法绑定到实例。

https://reactjs.org/docs/react-component.html#constructor

这篇关于什么时候在REACT中使用构造函数合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆