微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何等待AJAX​​响应,只有在渲染组件之后?

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

Obj tree

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

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

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

  return (
     index.id + " " + index.order.id
  )

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

我也尝试过类似的东西

  success: function(data){
    self.setState({
      response: data
    }, function(){
      self.forceUpdate();
    })
  }.bind(this)

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

解决方法:

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

  getinitialState: function(){
    return {
      // [{}] is weird, either use undefined (or [] but undefined is better).
      // If you use [], you loose the @R_99_4045@ion 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
    }
  },
  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
                });
            }
          }
        });
     }
  },
  // 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);
  },
  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>
      ) 
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐