使用React,如何在更改路径时触发浏览器选项卡中的浏览器加载指示器?

时间:2017-08-31 07:03:01

标签: javascript reactjs react-router

更改Facebook等网站上的页面会触发浏览器的加载指示,尽管有时可能不会进行整页重新加载。如何使用React实现类似的行为?

1 个答案:

答案 0 :(得分:0)

如果您正在使用react-router,您可以在客户端本身处理路由更改。您可以创建HOC以在路线更改时显示加载指示器。

import React from 'react';
import Loader from './Loader';

function withRouteLoader(WrappedComponent) {
  class AppWithRouteLoader extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        isLoading: false,
        loadedRoutes: props.location && [props.location.pathname],
      };
      this.updateIsLoading = this.updateIsLoading.bind(this);
    }

    componentWillMount() {
      this.unsubscribeHistory = this.props.router && this.props.router.listenBefore((location) => {
        if (this.state.loadedRoutes.indexOf(location.pathname) === -1) {
          this.updateIsLoading(true);
        }
      });
    }

    componentWillUpdate(newProps, newState) {
      const { loadedRoutes } = this.state;
      const { pathname } = newProps.location;

      if (loadedRoutes.indexOf(pathname) === -1 && newState.isLoading  === true) {
        this.updateIsLoading(false);
        this.setState({
          loadedRoutes: loadedRoutes.concat([pathname]),
        });
      }
    }

    componentWillUnmount() {
      this.unsubscribeHistory = undefined;
    }

    updateIsLoading(isLoading) {
      this.setState({ isLoading });
    }

    render() {
      return (
        <div>
          <Loader show={this.state.isLoading} />
          <WrappedComponent {...this.props} />
        </div>
      );
    }
  }

  AppWithRouteLoader.propTypes = {
    location: React.PropTypes.object,
    router: React.PropTypes.object,
  };

  return AppWithRouteLoader;
}

export default withRouteLoader;

你可以参考这个Boilterplate https://github.com/react-boilerplate/react-boilerplate。它实现了整个事情