React中loading界面处理

前几周,boss给出一个任务:在网站页面加载前设置一个loading界面。

设置loading界面,如果用户网络状况一般,或者用户执行请求操作频繁,可以让用户减少等待时间,有利于提升用户体验。那么具体怎样实现loading界面呢?查询资料进行实践,得出下面几个方案:

方案一:

在react框架中,根据组件的生命周期,在componentdidmount进行判断。在render中进行判断:当用户网络不好(没有获得相应内容),执行loading界面的内容;当用户网络获得请求,在componentdidmount中调用setState对state属性进行更改,对界面进行重新render,内容界面显示。

当然,如果有bootstrap框架或者reactstrap框架就更便于开发了。

componentDidMount() {
    const ID = this.props.ID;
    const path = this.props.path;
    // when get the response, change loading state, then render again
    this.props.getInformation(ID, path).then((response) => {
        this.setState({
          loading: false
        });
      })
  }

这是生命周期函数进行判断,之后在页面中进行二次渲染。

render() {
    // 页面初始加载
    if (this.state.loading === true) {
      return (
        <div className="empty-loading-page">
          <div className="lds-ripple page-centered"><div>
        </div>
      );
    }
    // 当请求执行完毕,再次渲染页面
    else {
      return (
        // codes of pages
    );
}

这需要使用reactstrap提供的组件,效果很好

方案二:

如果不使用loading组件,那么完全可以自己设置css和html。

当然这样的工作量就会大大增加(根据实际需求确定方案)。

猜你喜欢

转载自blog.csdn.net/weixin_41697143/article/details/81837145