我发现,当通过setState
设置类实例时,它会丢失其构造函数并成为plain object
。我在文档中看到setState
将值与当前状态合并,可能无法处理复杂类型。那么,国家是否应该是普通的内置型?
http://jsfiddle.net/58c8e7e3/1/
===== code ===
/** @jsx React.DOM */
//=============== transpiled through babeljs.io ======//
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Data = (function () {
function Data() {
_classCallCheck(this, Data);
}
Data.prototype.isLoading = function isLoading() {
return this.__state == 2;
};
return Data;
})();
//============
var Hello = React.createClass({
getInitialState: function() {
return new Data();
},
render: function() {
return (
<div>
State: <pre>{JSON.stringify(this.state)} proto: {this.state.constructor.name} </pre>
<button onClick={this.setXsimple}>setState</button>
</div>
);
},
setXsimple: function() {
this.setState(new Data());
}
});
React.renderComponent(<Hello name="World" />, document.body);
答案 0 :(得分:2)
是的,this.state
应该是一个普通的JavaScript对象。但是,您可以将复杂类型作为该对象的值:
/** @jsx React.DOM */
//=============== transpiled through babeljs.io ======//
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Data = (function () {
function Data() {
_classCallCheck(this, Data);
}
Data.prototype.isLoading = function isLoading() {
return this.__state == 2;
};
return Data;
})();
//============
var Hello = React.createClass({
getInitialState: function() {
return { data: new Data() };
},
render: function() {
return (
<div>
State: <pre>{JSON.stringify(this.state)} proto: {this.state.data.constructor.name} </pre>
<button onClick={this.setXsimple}>setState</button>
</div>
);
},
setXsimple: function() {
this.setState({ data: new Data() });
}
});
答案 1 :(得分:1)