Reactjs 组件的异步渲染

IT技术 javascript ajax asynchronous reactjs jquery-deferred
2021-01-29 22:27:32

我想在我的 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 方法中返回渲染。

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 请求结束?

3个回答

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

  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>;
      }
    });
    
  2. 将 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} />;
      }
    });
    
if (this.state.data)应该是if (this.state && this.state.data)因为有时状态可以为空。
2021-03-14 22:27:32
@Timo 嗯,在什么情况下会this.statenull
2021-03-19 22:27:32
我在 2017 年偶然发现了这个答案,这两个最好的解决方案仍然是最好的吗?
2021-03-26 22:27:32
@Timo 在构造函数中初始化状态
2021-03-27 22:27:32
@Dan React 基于 props 和 state 渲染 UI,所以核心概念将保持不变——执行 Ajax 请求,设置一些状态,然后重新渲染一些东西。然而,像高阶组件这样的模式变得越来越流行,展示了人们如何抽象出复杂性。
2021-04-08 22:27:32

组件异步渲染的基本示例如下:

import React                from 'react';
import ReactDOM             from 'react-dom';        
import PropTypes            from 'prop-types';

export default class YourComponent extends React.PureComponent {
    constructor(props){
        super(props);
        this.state = {
            data: null
        }       
    }

    componentDidMount(){
        const data = {
                optPost: 'userToStat01',
                message: 'We make a research of fetch'
            };
        const endpoint = 'http://example.com/api/phpGetPost.php';       
        const setState = this.setState.bind(this);      
        fetch(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        })
        .then((resp) => resp.json())
        .then(function(response) {
            setState({data: response.message});
        });
    }

    render(){
        return (<div>
            {this.state.data === null ? 
                <div>Loading</div>
            :
                <div>{this.state.data}</div>
            }
        </div>);
    }
}

异步状态管理(Playground

以下解决方案允许异步状态管理,如果正确实施,可用于 HTTP 相关要求。

要求

  • 只重新渲染消耗 observable 的元素。
  • 自动订阅和取消订阅 observable。
  • 支持多个联合观察。
  • 提供加载状态
  • 简单易行的实施

预期行为

return (
    <Async select={[names$]}>
        {result => <div>{result}</div>}
    </Async>
);

上面提供的示例将订阅 observable names$Async当 next 在 observable 上触发时组件的内容/子组件将重新渲染,不会导致当前组件重新渲染。

异步组件

export type AsyncProps<T extends any[]> = { select: { [K in keyof T]: Observable<T[K]> }, children: (result?: any[]) => JSX.Element };
export type AsyncState = { result?: any[] };

export default class Async<T extends any[]> extends Component<AsyncProps<T>, AsyncState> {

    private subscription!: Subscription;

    constructor(props: AsyncProps<T>) {
        super(props);
        this.state = {};
    }

    componentDidMount() {
        this.subscription = combineLatest(this.props.select)
            .subscribe(result => this.setState({ result: result as T }))
    }

    componentWillUnmount() {
        this.subscription.unsubscribe();
    }

    render() {
        return (
            <Fragment>
                {this.props.children(this.state.result)}
            </Fragment>
        );
    }

}