在react-router的路由之间显示一个简单的加载指示器

IT技术 javascript reactjs redux react-redux react-router
2021-05-19 12:11:37

我来自AngularJS世界,几天前开始用react-router,在AngularJS 中编写我的第一个 React 应用程序

app.directive('Loading', function($rootScope, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        template: '<p>Loading</p>'
        link: function(scope, element) {
            $rootScope.$on('$routeChangeStart', function(event, currentRoute, previousRoute) {
                element.removeClass('ng-hide');
            });

            $rootScope.$on('$routeChangeSuccess', function() {
                element.addClass('ng-hide');
            });
        }
    };
});

然后我只需添加<Loading></Loading>. 所以现在在我的 React 应用程序中,我有:

class App extends Component {
  render() {
    return (
       <Router>
        <div>
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/about">About</Link></li>
          </ul>

          <hr/>

          <Route exact path="/" component={Home}/>
          <Route path="/about" component={About}/>

        </div>
      </Router>


    );
  }
}

我的两个组件很简单:

class Home extends Component {
    render() {
        return (
            <h1>Home</h1>
        );
    }
}
class About extends Component {
    render() {
        return (
            <h1>About</h1>
        );
    }
}

我可以在不使用reduxJS 的情况下做到这一点吗?

2个回答

您可以在react中使用高阶组件以通用方式执行此操作。

看看是一个例子:

https://github.com/thejameskyle/react-loadable

如果你获取一些数据,我做了一个小包react-router-loading,它允许你显示加载指示器并在切换屏幕之前加载一些数据。

只需使用Switchand Routefrom this package 而不是react-router-dom

import { Switch, Route } from "react-router-loading";

loadingprops添加到您要等待的路线:

<Route path="/about" component={About} loading/>

然后在About组件 add中获取逻辑末尾的某处loadingContext.done();

import { LoadingContext } from "react-router-loading";
const loadingContext = useContext(LoadingContext);

const loading = async () => {
    //loading some data

    //call method to indicate that loading is done and we are ready to switch
    loadingContext.done();
};