在 React/React Native 中使用构造函数和 getInitialState 有什么区别? [英] What is the difference between using constructor vs getInitialState in React / React Native?
本文介绍了在 React/React Native 中使用构造函数和 getInitialState 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过两者可以互换使用.
I've seen both used interchangeably.
两者的主要用例是什么?有没有优点/缺点?一种更好的做法吗?
What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?
推荐答案
这两种方法不可互换.使用 ES6 类时应在构造函数中初始化 state,使用 React.createClass
时定义 getInitialState
方法.
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
.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { /* initial state */ };
}
}
相当于
var MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ };
},
});
这篇关于在 React/React Native 中使用构造函数和 getInitialState 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文