2015-06-18 56 views
4

我正在做2個基本的ajax調用2個不同的apis在我的ReactJs組件之一。雖然運行的呼叫(對我肯定知道正在和返回數據的URL)時,我得到:Reactjs this.state給予未捕獲的TypeError:無法讀取null的屬性'groupsData'

Uncaught TypeError: Cannot read property 'groupsData' of null 

這裏是單組分:

var BrowseWidgetBox = React.createClass({ 
       getGroupsApi: function(){ 
        $.ajax({ 
         url: this.props.groupsApi, 
         dataType: 'json', 
         type: 'GET', 
         success: function(groupsData){ 
          this.setState({groupsData: groupsData}); 
         }.bind(this), 
         error: function(xhr, status, err){ 
          console.error(this.props.groupsApi ,status, err.toString()); 
         }.bind(this) 
        }); 

       }, 
       getItemsApi: function() { 
       $.ajax({ 
         url: this.props.itemsApi, 
         dataType: 'json', 
         type: 'GET', 
         success: function(itemsData){ 
          this.setState({itemsData: itemsData}); 
         }.bind(this), 
         error: function(xhr, status, err){ 
          console.error(this.props.groupsApi ,status, err.toString()); 
         }.bind(this) 
        }); 
       }, 
       componentDidMount: function() { 
        this.getGroupsApi(); 
        this.getItemsApi(); 
       }, 
       render: function() { 
        return (<div className="BrowseWidgetBox"> 
           <MainMenu groupsData={this.state.groupsData} itemsData={this.state.itemsData} /> 
           <Display /> 
          </div>); 
       } 
      }); 



       React.render(
        <BrowseWidgetBox groupsApi="/*imagine a working url here*/" itemsApi="/*imagine a working url here*/" />, document.getElementById('widget-container') 
       ); 

有什麼明顯的我失蹤在reactJS/ajax方面?

回答

3

您應該添加getInitialState方法你的組件,你應該設置初始狀態

var BrowseWidgetBox = React.createClass({ 
    getInitialState: function() { 
     return {groupsData: {}, itemsData: {}}; 
    }, 
    // your code 
}); 
6

更實際的答案,取決於從使用非標準:

ES6類

export class Component extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { groupsData: {}, itemsData: {} }; 
    } 
    ... 
} 

ES7 +類

export class Counter extends React.Component { 
    state = { groupsData: {}, itemsData: {} }; 
    ... 
} 
相關問題