2015-08-17 11:29
浏览 248

Reactjs Ajax在获取json对象时返回第一个空数组

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() {
  url: '#########my_url#########',
  dataType: 'json',
  success: function(data) {
    this.setState({datas: data});

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushi8186
    doushi8186 2015-08-17 12:17

    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


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

    Basically this should work.

    点赞 评论