React createClass 和 Component 有什么区别?
以前是这样写的
let app = React.createClass({
getInitialState: function(){
// some thing
}
})
然后也看到用 React.Component,于是
class TodoApp extends React.Component{
getInitialState(){
// some thing
}
}
但是压根没有执行 getInitialState,控制台提示
Warning: getInitialState was defined on TodoApp, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
问:
-
createÇlass Component 区别,什么时候用什么?
-
生命周期的componentDidMount 的 component 又啥联系?
-
用Component形式又怎么初始化state?
Answers
React在ES6的实现中去掉了getInitialState这个hook函数,规定state在constructor中实现,如下:
Class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
...
}
Babel的Blog上还有一种实现方法,即直接使用赋值语句:
Class App extends React.Component {
constructor(props) {
super(props);
}
state = {}
...
}
官网上有提及两者:
The API (via 'extends React.Component') is similar to React.createClass with the exception of getInitialState. Instead of providing a separate getInitialState method, you set up your own state property in the constructor.
也就是说 通过es6类的继承实现时 state的初始化要在constructor中声明
class exampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {example: 'example'}
}
}