【问题标题】:When is it appropriate to use a constructor in REACT?什么时候适合在 REACT 中使用构造函数?
【发布时间】:2019-04-01 00:25:01
【问题描述】:

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

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

有可能是我的 ES6 知识达不到标准。

【问题讨论】:

    标签: javascript reactjs react-native constructor es6-class


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 但是我可以在不需要构造函数的情况下初始化我的状态并使用箭头函数,所以我不需要绑定。这是否意味着构造函数根本没有用? stackoverflow.com/questions/42993989/…
    【解决方案2】:

    构造函数根本不需要

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

    技术上这些被称为类属性,它可能很快就会出现在原生 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>
    }
    }
    

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-09
        • 1970-01-01
        • 2013-06-17
        • 2013-06-21
        • 2010-11-29
        • 1970-01-01
        • 1970-01-01
        • 2015-01-23
        相关资源
        最近更新 更多