Reactjs 组件的异步渲染 [英] Reactjs async rendering of components

查看:73
本文介绍了Reactjs 组件的异步渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 ajax 请求完成后呈现我的组件.

I want to render my component after my ajax request is done.

下面你可以看到我的代码

Below you can see my code

var CategoriesSetup = React.createClass({

    render: function(){
        var rows = [];
        $.get('http://foobar.io/api/v1/listings/categories/').done(function (data) {
            $.each(data, function(index, element){
                rows.push(<OptionRow obj={element} />);
            });
           return (<Input type='select'>{rows}</Input>)

        })

    }
});

但我收到以下错误,因为我在我的 ajax 请求的 done 方法中返回渲染.

But i get the error below because i am returning render inside the done method of my ajax request.

未捕获的错误:不变违规:CategoriesSetup.render():必须返回有效的 ReactComponent.您可能返回了未定义、数组或其他无效对象.

有没有办法在开始渲染之前等待我的 ajax 请求结束?

Is there a way to wait for my ajax request to end before start rendering?

推荐答案

有两种方法可以解决这个问题,你选择哪种方法取决于哪个组件应该拥有数据和加载状态.

There are two ways to handle this, and which you choose depends on which component should own the data and the loading state.

  1. 将 Ajax 请求移动到父级并有条件地呈现组件:

  1. Move the Ajax request into the parent and conditionally render the component:

var Parent = React.createClass({
  getInitialState: function() {
    return { data: null };
  },

  componentDidMount: function() {
    $.get('http://foobar.io/api/v1/listings/categories/').done(function(data) {
      this.setState({data: data});
    }.bind(this));
  },

  render: function() {
    if (this.state.data) {
      return <CategoriesSetup data={this.state.data} />;
    }

    return <div>Loading...</div>;
  }
});

  • 将 Ajax 请求保留在组件中,并在加载时有条件地呈现其他内容:

  • Keep the Ajax request in the component and render something else conditionally while it's loading:

    var CategoriesSetup = React.createClass({
      getInitialState: function() {
        return { data: null };
      },
    
      componentDidMount: function() {
        $.get('http://foobar.io/api/v1/listings/categories/').done(function(data) {
          this.setState({data: data});
        }.bind(this));
      },
    
      render: function() {
        if (this.state.data) {
          return <Input type="select">{this.state.data.map(this.renderRow)}</Input>;
        }
    
        return <div>Loading...</div>;
      },
    
      renderRow: function(row) {
        return <OptionRow obj={row} />;
      }
    });
    

  • 这篇关于Reactjs 组件的异步渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆