2015-05-04 79 views
0

我發現,當通過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); 

回答

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() }); 
    } 
}); 
+0

謝謝。如果數據對象進一步作爲道具傳遞給子組件,您認爲使用普通對象或數組更好嗎?我想知道使用普通對象是否有效執行更改檢測。 – bsr

+1

道具可以是任何東西。更改檢測對於不可變值是最簡單的,因爲您可以簡單地進行參考平等。 –

1

docs

第一個參數可以是對象(包含零個或多個鍵 更新)或返回包含要更新的密鑰的對象 的函數(狀態和道具)。

我假設他們指的是這裏的普通對象,而不是類或數組f。恩。