在构造函数中声明React状态还是在构造函数外声明?

4

声明 state 时,是否在构造函数之外有任何区别?

这里有一个组件的示例:

class BurgerBuilder extends Component {
  state = {
    ingredients: {
      salad: 0,
      bacon: 0,
      cheese: 0,
      meat: 0
    },
    totalPrice: 30
  };
  ....
}

在这里,我声明了一个名为“state”的变量,其中包含组件的变量,但我没有调用构造函数。

而当我声明如下时:

class BurgerBuilder extends Component {
  constructor() {
    super();
    this.state = {
      ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
      },
      totalPrice: 30
    };
  }
  ....
}

我发现我可以在这两种解决方案中都使用this.setState,并且在我的项目中没有真正的区别。是否有最佳实践,在何处使用什么。
1个回答

7
有什么区别吗?在何处使用最佳实践?
它们几乎是相同的。声明不包含 constructor() 的状态的语法是糖语法
第一个示例中使用的是类字段声明。 (此提案于2017年7月达到第3阶段)。
简而言之,该提案允许我们使用更简单的语法声明类字段,无需使用 constructor()
例如,这些代码是使用ES2015编写的。
class Counter extends HTMLElement {
  constructor() {
    super();
    this.onclick = this.clicked.bind(this);
    this.x = 0;
  }

  clicked() {
    this.x++;
    window.requestAnimationFrame(this.render.bind(this));
  }

  connectedCallback() { this.render(); }

  render() {
    this.textContent = this.x.toString();
  }
}
window.customElements.define('num-counter', Counter);

通过使用类字段声明,它们将会是这样的:
class Counter extends HTMLElement {
  x = 0;

  clicked() {
    this.x++;
    window.requestAnimationFrame(this.render.bind(this));
  }

  constructor() {
    super();
    this.onclick = this.clicked.bind(this);
  }

  connectedCallback() { this.render(); }

  render() {
    this.textContent = this.x.toString();
  }
}
window.customElements.define('num-counter', Counter);

使用这种语法的好处:

通过预先声明字段,类定义变得更加自我说明;实例经历的状态转换更少,因为申明的字段始终存在。


参考:JavaScript类字段声明


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接