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

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

问题描述

我了解 C++ 等 OOP 语言中构造函数的概念.但是,我不完全确定何时在 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>
       )
    }
}

为了简洁起见,我将保持示例简短.但是,为什么需要构造函数?您是否需要在子组件中为 props 设置一个构造函数?

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天全站免登陆