什么时候适合在 REACT 中使用构造函数?

When is it appropriate to use a constructor in REACT?

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

渲染子组件时,需要子组件中有构造函数吗?例如:

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>
       )
    }
}

为了简洁起见,我将保持示例简短。但是,为什么需要构造函数?你需要在道具的子组件中使用构造函数吗?

可能是我的 ES6 知识不够全面。

如果你不初始化状态也不绑定方法,你就不需要为你的 React 组件实现构造函数。

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

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

  • 正在通过将对象分配给 this.state 来初始化本地状态。
  • 正在将事件处理程序方法绑定到实例。

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

Linke 在您的示例中,当您需要初始化状态或绑定一些事件侦听器函数时,使用构造函数很有用

  1. <element onClick={this.handler} />
  2. this.handler = this.bind.handler(this); 在构造函数中

构造函数根本不需要

状态初始化可以直接在 class 的主体中完成,函数可以分配给属性,如下所述,

技术上这些被称为 class 属性,它可能很快就会出现在原生 javascript 中,但是因为我们几乎所有人都在 React 项目中使用 Babel 转译器,所以我们可以使用该语法

class Comp extends React.Component {
/* 
 * generally we do not need to put the props in state, but even if we need to.
 * then it is accessible in this.props as shown below 
**/
state={ first: 1, second: this.props.second } 

handler= (token) => {
 this.setState(prevState => ({first: prevState.first+1}));
}

render() {
 return <div onClick={this.handler}>{this.state.first} and {this.state.second } </div>
}
}

在此处阅读有关 class 属性和从 React class 组件中删除构造函数的更多详细信息。 https://hackernoon.com/the-constructor-is-dead-long-live-the-constructor-c10871bea599