代码之家  ›  专栏  ›  技术社区  ›  Enrique Moreno Tent

在ReactJS中初始化状态的不同方法

  •  0
  • Enrique Moreno Tent  · 技术社区  · 6 年前

    class MyComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = { ... }
        }
    }
    

    直接在课堂上

    class MyComponent extends React.Component {
        state = { ... }
    }
    

    组件中的willmount

    class MyComponent extends React.Component {
        ComponentWillMount() {
            this.state = { ... }
        }
    }
    

    选项的多样性常常使我感到困惑,使我很难决定如何在组件中设置状态。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Community Ramakrishna.p    4 年前

    在构造函数中

    这是将属性附加到类实例的“常规”标准方法。

    直接上课

    class fields proposal 目前正处于第三阶段(2018年10月1日)。你需要 babel/plugin-proposal-class-properties

    constructor which is deprecated by the way

        2
  •  0
  •   Tarek Essam    6 年前

    现在您应该知道componentWillMount已被弃用,您不应该使用它。至于在构造函数中设置state或as class属性是相同的,您可以使用其中任何一个,我更喜欢class属性。

        3
  •  0
  •   Estus Flask    6 年前

    这是 class field proposal :

    class MyComponent extends React.Component {
        state = { ... }
    }
    

    它是用于:

    class MyComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = { ... }
        }
    }
    

    前者较短,除非需要显式构造函数,否则由于其简洁性,在transpiled React应用程序中可以被认为是更好的方法。

    ComponentWillMount 生命周期挂钩 was renamed to UNSAFE_componentWillMount and deprecated 以建造商为受益人:

    不安全的\u componentWillMount()在装载发生之前被调用。它在render()之前调用,因此在此方法中同步调用setState()不会触发额外的呈现。通常,我们建议使用构造函数()来初始化状态。