Javascript Reactjs this.state给出未捕获的TypeError:无法读取属性';集团数据';空的
我正在我的一个ReactJs组件中对两个不同的API进行两个基本ajax调用。尽管如此,在运行调用时(在我确定正在运行并返回数据的URL上),我会收到:Javascript Reactjs this.state给出未捕获的TypeError:无法读取属性';集团数据';空的,javascript,ajax,reactjs,Javascript,Ajax,Reactjs,我正在我的一个ReactJs组件中对两个不同的API进行两个基本ajax调用。尽管如此,在运行调用时(在我确定正在运行并返回数据的URL上),我会收到: Uncaught TypeError: Cannot read property 'groupsData' of null 以下是单个组件: var BrowseWidgetBox = React.createClass({ getGroupsApi: function(){
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')
);
var BrowseWidgetBox=React.createClass({
getGroupsApi:function(){
$.ajax({
url:this.props.groupsApi,
数据类型:“json”,
键入:“GET”,
成功:功能(组数据){
this.setState({groupsData:groupsData});
}.绑定(此),
错误:函数(xhr、状态、错误){
console.error(this.props.groupsApi,status,err.toString());
}.绑定(此)
});
},
getItemsApi:函数(){
$.ajax({
url:this.props.itemsApi,
数据类型:“json”,
键入:“GET”,
成功:功能(itemsData){
this.setState({itemsData:itemsData});
}.绑定(此),
错误:函数(xhr、状态、错误){
console.error(this.props.groupsApi,status,err.toString());
}.绑定(此)
});
},
componentDidMount:function(){
这个.getGroupsApi();
这个.getItemsApi();
},
render:function(){
返回(
);
}
});
反应(
,document.getElementById('widget-container'))
);
在reactJS/ajax方面有什么明显的不足之处吗 您应该将方法添加到组件中,并在其中设置初始状态
var BrowseWidgetBox = React.createClass({
getInitialState: function () {
return {groupsData: {}, itemsData: {}};
},
// your code
});
更多实际答案,取决于使用的标准: 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: {} };
...
}