将State初始化为类属性或在构造函数中[ReactJS] [英] Initialise State as a class property or in constructor [ReactJS]

查看:94
本文介绍了将State初始化为类属性或在构造函数中[ReactJS]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到两个案例设置了默认状态,例如:

I've seen tow cases set default state like:

class Page extends Component {
  state = {
    page: 0,
  };
}

vs

class Page extends Component {
  constructor(props) {
    super(props);
    this.state = { page: 0 };
  }
}

使用第一种方法是否不好?我在哪里可以找到有关它的更多信息?还是该ecmascript的功能命名方式?

Use first variant Is it bad practice? Where can i find out more information about it? Or how this ecmascript's feature is named?

推荐答案

如果您具有 stage-,则可以使用第一个变体, 2个预置,配置了babel。它是类属性语法,不包含在ES7提议中,但可作为babel的第二阶段预设使用。然而,使用第一或第二变体是优先事项。它们都转换为完全相同的东西。

You can use the first variant if you have stage-2 preset configured with babel. It is a class property syntax and is not event included in ES7 proposal, however it is available as stage-2 preset with babel. However using the first or the second variant is a matter of preference. They both transpile to the exact same thing.

第一种方法:

First method:

第二种方法

Second method

这篇关于将State初始化为类属性或在构造函数中[ReactJS]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆