如何等待AJAX​​响应并且只有在渲染组件之后?

Tom*_*oad 37 javascript ajax reactjs

我的一个React组件有问题.我认为在React呈现ChildComp组件之前,AJAX不会从外部服务器加载所有内容.

Obj树

在上面你可以看到来自服务器的响应树.这是我的组件代码:

var ChildComp = React.createClass({
  getInitialState: function(){
    return {
      response: [{}]
    }
  },
  componentWillReceiveProps: function(nextProps){
    var self = this;

    $.ajax({
      type: 'GET',
      url: '/subscription',
      data: {
        subscriptionId: nextProps.subscriptionId //1
      },
      success: function(data){
        self.setState({
          response: data
        });
        console.log(data);
      }
    });
  },
  render: function(){
      var listSubscriptions = this.state.response.map(function(index){
        return (
          index.id
        )
      });
      return (
        <div>
          {listSubscriptions}
        </div>
      ) 
  }
});
Run Code Online (Sandbox Code Playgroud)

这工作正常,但如果我改变我的回报:

  return (
     index.id + " " + index.order.id
  )
Run Code Online (Sandbox Code Playgroud)

id未定义.以及订单对象的所有其他属性.为什么会这样?如果我console.logsuccess功能后回复它会提供所有数据(如图片所示).我的猜测是,当React渲染组件时,只加载第一个对象,然后加载所有其他内部对象.我真的不能说是不是这样(听起来很奇怪),也不能说如何解决这个问题.

我也尝试过类似的东西

  success: function(data){
    self.setState({
      response: data
    }, function(){
      self.forceUpdate();
    })
  }.bind(this)
Run Code Online (Sandbox Code Playgroud)

但是在我console.log(data)被触发之前仍然重新渲染.如何等待AJAX​​响应并且只有在渲染组件之后?

Seb*_*ber 30

这是您的代码重做了一些修改部分的注释

  getInitialState: function(){
    return {
      // [{}] is weird, either use undefined (or [] but undefined is better).
      // If you use [], you loose the information of a "pending" request, as 
      // you won't be able to make a distinction between a pending request, 
      // and a response that returns an empty array
      response: undefined
    }
  },
Run Code Online (Sandbox Code Playgroud)
  loadSubscriptionData: function(subscriptionId){
    var self = this;

    // You probably want to redo the ajax request only when the 
    // subscriptionId has changed (I guess?)
    var subscriptionIdHasChanged = 
       (this.props.subscriptionId !== subscriptionId)

    if ( subscriptionIdHasChanged ) {
        // Not required, but can be useful if you want to provide the user
        // immediate feedback and erase the existing content before 
        // the new response has been loaded
        this.setState({response: undefined});

        $.ajax({
          type: 'GET',
          url: '/subscription',
          data: {
            subscriptionId: subscriptionId //1
          },
          success: function(data){

            // Prevent concurrency issues if subscriptionId changes often: 
            // you are only interested in the results of the last ajax    
            // request that was made.
            if ( self.props.subscriptionId === subscriptionId ) {
                self.setState({
                  response: data
                });
            }
          }
        });
     }
  },
Run Code Online (Sandbox Code Playgroud)
  // You want to load subscriptions not only when the component update but also when it gets mounted. 
  componentDidMount: function(){
    this.loadSubscriptionData(this.props.subscriptionId);
  },
  componentWillReceiveProps: function(nextProps){
    this.loadSubscriptionData(nextProps.subscriptionId);
  },
Run Code Online (Sandbox Code Playgroud)
  render: function(){

      // Handle case where the response is not here yet
      if ( !this.state.response ) {
         // Note that you can return false it you want nothing to be put in the dom
         // This is also your chance to render a spinner or something...
         return <div>The responsive it not here yet!</div>
      }

      // Gives you the opportunity to handle the case where the ajax request
      // completed but the result array is empty
      if ( this.state.response.length === 0 ) {
          return <div>No result found for this subscription</div>;
      } 


      // Normal case         
      var listSubscriptions = this.state.response.map(function(index){
        return (
          index.id
        )
      });
      return (
        <div>
          {listSubscriptions}
        </div>
      ) 
  }
Run Code Online (Sandbox Code Playgroud)