初始化状态-使用构造函数与不使用构造函数之间的区别-React Native

时间:2018-07-25 01:52:05

标签: react-native

使用构造函数:

import { Text } from 'react-native';
import Component from 'react';

class Blink extends Component {
    constructor(props) {
      super(props);
      this.state = {test: "Hello"};
}

没有构造函数:

import { Text } from 'react-native';
import Component from 'react';

class Blink extends Component {
    state = { test:"Hello" }
}

代码以相同的方式工作。但是有什么区别呢?哪个更好?

1 个答案:

答案 0 :(得分:2)

It's just a matter of preference! Here's an article I found about the different ways to initialize a component: https://daveceddia.com/where-initialize-state-react/