2015-10-23 35 views
1

我一直在跟着一些React的教程,我開始自己構建一個應用程序。我遇到了有關組件的情況,我想知道是否是這種情況下的最佳做法。請注意,我只是使用react-rails;現在沒有助焊劑或任何東西。React-Rails:使用ajax加載初始數組狀態

設置初始狀態的數組,其價值得到通過Ajax設置,並有在初始該陣列顯示器呈現

這裏就是我想要做的:(剝離下來爲簡單起見)

var ShoutList = React.createClass({ 
    getInitialState: function(){ 
     return {shouts: []}; 
    }, 
    componentDidMount: function(){ 
     var component = this; 
     $.get('/api/shouts.json', function(data){ 
      component.setState({shouts: data}); 
     }); 
    }, 
    render: function(){ 
     return (
      <div> 
      {this.state.shouts[0].shout} 
      </div>);    
    } 
}); 

所以,如果我有這個權利,在這種事情去運行的順序如下:

  1. 上的負載,getInitialState設置呼喊一個空陣列
  2. 由於試圖訪問空陣列上的shout屬性,渲染被調用並出錯
  3. ComponentDidMount被調用並將呼叫狀態設置爲從ajax調用接收到的數據。 **當我嘗試在ComponentWillMount中執行此操作時出現錯誤**
  4. 由於狀態已更改,所以再次調用渲染,但是這次喊出[0] .shout將包含數據。

所以我報錯了在步驟2,我的解決辦法如下:

var ShoutList = React.createClass({ 
    getInitialState: function(){ 
     return {shouts: []}; 
    }, 
    componentDidMount: function(){ 
     var component = this; 
     $.get('/api/shouts.json', function(data){ 
      component.setState({shouts: data}); 
     }); 
    }, 
    emptyShouts: function(){ 
     return(<div>No Shouts Yet!</div>); 
    }, 
    shoutsList: function(){ 
     return(<div>{this.state.shouts[0].shout}</div>); 
    }, 
    render: function(){ 
     if(this.state.shouts.length > 0){ 
      return this.shoutsList(); 
     }else { 
      return this.emptyShouts(); 
     } 
    } 
}); 

操作就像我需要它,但有設置初始狀態的數組值的更好的方法與阿賈克斯和它加載在初始渲染,而不必這樣做,如果陳述?

謝謝!

回答

0

沒有使用Flux,我會說你的實現是解決這個問題的少數幾種方法之一。另一種方法是你render的迴歸之前有邏輯:

... 
render: function() { 
    var renderedShout; 
    if (typeof this.state.shouts[0] === "undefined") { 
    renderedShout = <div>No Shouts Yet!</div>; 
    } else { 
    renderedShout = <div>{this.state.shouts[0].shout}</div>; 
    } 

    return renderedShout; 
} 

做這種方式的好處是,你只會有一個返回這可能使其更清晰了,從長遠來看讀者。

0

如果你願意,你可以嘗試在您的預編輯代碼這種變化:

var ShoutList = React.createClass({ 
    getInitialState: function(){ 
     return {shouts: []}; 
    }, 
    componentDidMount: function(){ 
     var component = this; 
     $.get('/api/shouts.json', function(data){ 
      component.setState({shouts: data}); 
     }.bind(this), 'json'); 
    }, 
    render: function(){ 
     return (
      <div> 
      {this.state.shouts[0].shout} 
      </div>);    
    } 
}); 

bind$.get調用進行調用的組件。它從那裏按預期工作。