Reactjs中的this.state出现Uncaught TypeError: Cannot read property 'groupsData' of null错误

4

我正在ReactJs组件中进行基本的Ajax调用,调用2个不同的API。但是,当运行调用(在我确定可用并返回数据的URL上),我收到以下错误信息:

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方面,我是否错过了什么显而易见的东西?

2个回答

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: {} };
  ...
}

3
你应该在组件中添加 getInitialState 方法,用于设置初始状态。
var BrowseWidgetBox = React.createClass({
   getInitialState: function () {
      return {groupsData: {}, itemsData: {}};
   },
   // your code
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接