【问题标题】:Declaring React state, in constructor, versus out of constructor在构造函数中与在构造函数外声明 React 状态
【发布时间】:2019-04-15 04:51:42
【问题描述】:

声明stateout of constructor有什么不同吗?

我这里有一个组件的例子:

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 用于这两种解决方案,并且我的项目没有真正的区别。是否有最佳实践,关于在哪里使用什么。

【问题讨论】:

    标签: reactjs components state


    【解决方案1】:

    有什么不同吗?是否有最佳实践,关于使用什么 在哪里?

    它们几乎相同。不带contructor() 声明state 的语法是syntactic sugar


    您在第一个示例中使用的是Class field declarations。 (该提案于 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 field declarations,它们将是这样的:

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

    使用这种语法的好处:

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


    参考:Class field declarations for JavaScript

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 2013-05-02
      • 2011-03-12
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2011-04-19
      • 2022-01-15
      • 2020-09-13
      相关资源
      最近更新 更多