在React / React Native中使用构造函数与getInitialState有什么区别? [英] What is the difference between using constructor vs getInitialState in React / React Native?

查看:104
本文介绍了在React / React Native中使用构造函数与getInitialState有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到两者可以互换使用。



两者的主要用例是什么?有优点/缺点吗?

解决方案

这两种方法不可互换。使用ES6类时,应在构造函数中初始化状态,并使用 React.createClass 时定义 getInitialState 方法。 / p>

请参阅关于ES6类的官方React文档

  class MyComponent扩展了React .Component {
构造函数(props){
超级(props);
this.state = {/ *初始状态* /};
}
}

等于

  var MyComponent = React.createClass({
getInitialState(){
return {/ *初始状态* /};
},
});


I've seen both used interchangeably.

What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?

解决方案

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

is equivalent to

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

这篇关于在React / React Native中使用构造函数与getInitialState有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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