如何在$ .get()完成之前等待在react.js中呈现视图?

时间:2015-10-25 08:42:51

标签: javascript jquery facebook reactjs reactjs-flux

您好我在reactjs中编写了一个聊天客户端,并希望使用从REST调用中检索到的数据来呈现我的组件。但是,我的组件在REST请求返回数据之前呈现;这会导致错误,因为我在我的子组件中调用this.props。

var MainChat = React.createClass({
getInitialData: function(){
    var c = []
    $.get("http://127.0.0.1:8888/test/sampledata.php?user=123", function(data, status) {
        console.log("Data: "+ data+ "\nStatus: " + status);
        c = data    
    })
},
getInitialState: function() {
    return {
        chatId : "",
        chats : this.getInitialData(),
        //chats: this.props.chats
    };
},
handleClickOnLeftUser: function(data){
    console.log("handleClickOnLeftUser");
    // console.log("chat id is"); 
    // console.log(data.chatID); 
    this.setState({chatID: data.chatID});
},

render: function() {
    console.log("main:render")
    console.log(this.props.chats);


    var theThreadIWantToPass = {};
    for(var i = 0; i < this.state.chats.length; i++)
    {
        console.log("chat: " + this.state.chats[i].chatID);
        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} // ***important
                />
            </div>
            <div>
                <RightMessageBox chat={theThreadIWantToPass} />
            </div>
        </div>
    );
}
});

2 个答案:

答案 0 :(得分:2)

在您的情况下,您需要使用方法componentDidMount,如此

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>
    );
  }
});

注意 - 使用"async": false这是不好的做法

答案 1 :(得分:1)

暂时找到了一个hackish修复程序(至少在有人回答之前)。我目前的解决方案是通过设置

来阻止jQuery使用回调
     $.ajaxSetup({ "async": false})

在我调用Jquery的get()函数之前。

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
    };
},