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

标签 javascript reactjs react-router

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

最佳答案

如果您使用的是 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;

你可以引用这个样板https://github.com/react-boilerplate/react-boilerplate .它实现了整个事情

关于javascript - 使用 React,如何在更改路由时在浏览器选项卡中触发浏览器加载指示器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45975233/

相关文章:

reactjs - 如何在 React 中重构我的 App.js 页面路由?最好的做法是什么?

java - Android:其他人可以从 apk 文件中或安装后看到其中的 Java 代码和字符串(例如 WebView 的 Javascript 命令)吗?

javascript - 检测 URL 的最后一部分不起作用 - PHP

javascript - React 15.1.0,将整个状态从 parent 传递给 child

javascript - 如何在两个 react 组件之间建立共享状态?

javascript - 如何在渲染后根据另一个状态使用 setState 更新状态?

javascript - 我在尝试运行机器人命令时收到此错误

javascript - XML 通过属性值删除节点 JavaScript

javascript - React Router Dom 不渲染任何组件

reactjs - 项目中出现错误 - 未捕获的 ReferenceError : Raven is not defined