小编典典

ReactJS组件的异步渲染

reactjs

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

在下面您可以看到我的代码

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方法内返回render。

Uncaught Error: Invariant Violation: CategoriesSetup.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

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


阅读 344

收藏
2020-07-22

共1个答案

小编典典

有两种处理方法,您可以选择哪种方法取决于应该拥有数据的组件和加载状态。

  1. 将Ajax请求移至父级并有条件地渲染该组件:
        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>;
      }
    });
  1. 将Ajax请求保留在组件中,并在加载时有条件地渲染其他内容:
        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} />;
      }
    });
2020-07-22