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

Web*_*eam 4 javascript constructor reactjs react-native es6-class

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

呈现子组件时,子组件中是否需要构造函数?例如:

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>
       )
    }
}
Run Code Online (Sandbox Code Playgroud)

为了简洁起见,我将简短示例。但是,为什么需要构造函数?您是否需要在子组件中使用一个构造函数来构造道具?

我的ES6知识可能还没有完全解决。

wan*_*ang 12

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

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

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

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

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

  • 但是我可以在不需要构造函数的情况下初始化状态并使用箭头函数,因此不需要绑定。这是否意味着构造函数根本没有用?/sf/ask/3009579261/ (2认同)

Aks*_*ain 8

构造函数是不是在所有需要。

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

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

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>
}
}
Run Code Online (Sandbox Code Playgroud)

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