使用构造函数和state = {}在react组件中声明状态有什么区别? [英] What is the difference between using constructor vs state = {} to declare state in react component?

查看:323
本文介绍了使用构造函数和state = {}在react组件中声明状态有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有两种方法可以在类组件中声明状态,如下所示

I found there is two way to declare state in class component like below

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: 'John'
        }
    }

    render() {
        return  <div>{this.state.name}</div>
    }

}

class App extends Component {
    state = {
       name: 'John'
    }

    render() {
        return  <div>{this.state.name}</div>
    }

}

这两者有什么区别?

推荐答案

它们大致相同。区别在于第二个示例中的初始化程序在构造函数之前执行。

They are roughly equivalent. The significant difference is that the initializer in the second example is executed before constructor.

第二种方法使用类别字段提案。

它是还不是ECMAScript标准的一部分,所以你需要正确设置转换器以使用第二种方法。

It is not a part of ECMAScript standard yet so you need to set up transpiler properly to use the second approach.

UPD 看看通天输出,以更好地理解领域例如如何使用公共工作。

UPD Take a look at Babel output to better understand how public instance fields work.

这篇关于使用构造函数和state = {}在react组件中声明状态有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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