如何使用 ajax 优雅地渲染 React.js 组件

How to gracefully render React.js Components with ajax

我正在开发一个 React.js 应用程序,所有页面的组件都包含一些从 API 获取的数据,问题是所有页面在加载时看起来都很奇怪,因为硬编码文本和设计元素首先加载,当获取数据时,所有内容都会被填充。在单页应用程序中或特别是在 React.js 中是否有通用的方法可以做到这一点,这样页面在加载时看起来不会很奇怪?

我们最近遇到了类似的问题,这里概述了我们是如何处理它的:

1) 给状态添加一个loading键,初始设置为true
2)当AJAX请求returns数据时,设置loadingfalse
3) In render() 方法 return 加载指示器/微调器时 loadingtrue

这是一个演示:http://codepen.io/PiotrBerebecki/pen/ozaaPm 和完整代码:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      time: null,
      loading: true
    };
  }

  componentDidMount() {  
    axios.get(this.props.url)
      .then(response => {
        this.setState({
          time: response.data.time,
          loading: false
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    let content;

    if (this.state.loading) {
      content = 'Loading...'
    } else {
      content = <p>Current time is: {this.state.time}</p>;
    }

    return (
      <div>
        {content}
      </div>
    );
  }
}


ReactDOM.render(
  <App url={"http://date.jsontest.com/"} />,  document.getElementById('content')
);