在React / React Native中使用构造函数与getInitialState有什么区别?

reactjs React.js

Green神乐

2020-03-09

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

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

第318篇《在React / React Native中使用构造函数与getInitialState有什么区别?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
梅神乐 2020.03.09

如今,我们不必在组件内部调用构造函数-我们可以直接调用state={something:""},否则以前我们首先要声明具有的构造函数super()以继承React.Component类中的所有内容,然后在构造函数内部初始化状态。

If using React.createClass then define initialize state with the getInitialState method.

Gil梅 2020.03.09

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

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

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

相当于

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android