您好,我正在用 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>
    );
}
});

最佳答案

在您的情况下,您需要使用方法 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 这是不好的做法

关于javascript - 如何等待在 react.js 中渲染 View 直到 $.get() 完成?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33327755/

10-12 06:32