我發現,當通過setState
設置類實例時,它會丟失其構造函數併成爲plain object
。我在文檔setState
中看到,該值與當前狀態合併,可能無法處理複雜類型。那麼,國家應該是普通的內建式嗎?setState更改構造函數類型
http://jsfiddle.net/58c8e7e3/1/
=====代碼===
/** @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);
謝謝。如果數據對象進一步作爲道具傳遞給子組件,您認爲使用普通對象或數組更好嗎?我想知道使用普通對象是否有效執行更改檢測。 – bsr
道具可以是任何東西。更改檢測對於不可變值是最簡單的,因爲您可以簡單地進行參考平等。 –