简体   繁体   中英

Reactjs Ajax returns first empty array while getting json object

I have a problem. I am learning React js and I have a template which i must edit. I need to add some ajax methods for getting and sending info. I manage to do some of those actions but now I have a problem.

I have php scripts which is getting me json_encode.

getCategories: function() {
$.ajax({
  url: '#########my_url#########',
  dataType: 'json',
  success: function(data) {
    this.setState({datas: data});
  }.bind(this)
});
},

and I have this

getInitialState: function() {
  return {datas: []};
},

The problem is I always get firstly the empty array and then the result. And when I try to work with it, it gets me error because it tries to map the empty array. This is the console.log before I try to play with the object.

[HMR] Waiting for update signal from WDS...

[]

[WDS] Hot Module Replacement enabled
[Object, Object, Object, Object]

How can I make it to work after the object is full?

First option: render your view on ajax call success

Second option: anticipate the case your state.datas is still empty

for example if you're working in your render function try:

   { this.state.datas ? <div> Loading </div> : <....

Above is JSX syntax

Hope it helps

EDIT:

if(this.state.datas.length == 0) {
    var mycomponent =<div> Loading ... </div>;
} else {
   var mycomponent = this.state.datas;
}

Basically this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM