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

查看:36
本文介绍了使用构造函数与 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>
    }

}

这两者有什么区别?

推荐答案

它们大致等效.显着的区别是第二个例子中的初始化器在constructor之前执行.

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

第二种方法使用 class fields 提案.

The second approach uses class fields proposal.

它还不是 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天全站免登陆