How to wait to render view in react.js until $.get() is complete?

北慕城南 提交于 2019-12-04 13:24:19

In your case you need use method componentDidMount, like so

var MainChat = React.createClass({

  getInitialData: function() {
    var url = 'http://127.0.0.1:8888/test/sampledata.php?user=123';

    $.get(url, function(data, status) {
        this.setState({ chats: data });        
    }.bind(this))
  },

  componentDidMount: function () {
    this.getInitialData();
  },

  getInitialState: function() {
    return {
      chatId: '',
      chats: []
    };
  },

  handleClickOnLeftUser: function(data){
    this.setState({ chatID: data.chatID });
  },

  render: function() {
    var theThreadIWantToPass = {};

    for(var i = 0; i < this.state.chats.length; i++) {
      if (this.state.chats[i].chatID === this.state.chatID) {
        theThreadIWantToPass = this.state.chats[i];
        break;
      }
    }

    return (
      <div className="chatapp">
        <div className="thread-section">
          <div className="thread-count"></div>
          <LeftUserList
              chats={this.state.chats}
              clickFunc={this.handleClickOnLeftUser} />
        </div>

        <div>
          <RightMessageBox chat={theThreadIWantToPass} />
        </div>
      </div>
    );
  }
});

Note - using "async": false this is bad practice

laycat

Found a hackish fix for the time being (at least until someone answers). My current solution is to prevent jQuery from using callbacks by setting

     $.ajaxSetup({ "async": false})

before I call Jquery's get() function.

getInitialData: function(){
    var c = []
    $.ajaxSetup({ "async": false})
    $.get("http://127.0.0.1:8888/test/sampledata.php?user=123", function(data, status) {
        console.log("Data: "+ data+ "\nStatus: " + status);
        c = data    
    })
    return c
},
getInitialState: function() {
    return {
        chatId : "",
        chats : this.getInitialData(),
        //chats: this.props.chats
    };
},
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!