redux 在react router中的路由之间显示简单的负载指示符

lsmepo6l  于 2023-02-19  发布在  React
关注(0)|答案(3)|浏览(119)

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

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来执行此操作吗?

eqfvzcg8

eqfvzcg81#

你可以在react中使用高阶分量来以一般的方式完成这一点。
Look是一个例子:
https://github.com/thejameskyle/react-loadable

hpxqektj

hpxqektj2#

如果你提取一些数据,我做了一个小包react-router-loading,它允许你在切换屏幕之前显示加载指示器并加载一些数据。
只需使用此软件包中的SwitchRoute,而不要使用react-router-dom

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

添加loading prop 到你想等待的路线:

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

然后在About组件中的获取逻辑的末尾添加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();
};
a0x5cqrl

a0x5cqrl3#

我认为通过使用useLayoutEffect,你可以在每一个路线变化上放置一个加载器。我任何人有问题请随时ping我。

import { useLayoutEffect, useState } from "react";
import RoutesWrapper from "./components/RoutesWrapper";
import Loader from "./components/Loader";
import { useLocation } from "react-router-dom";
function App() {
  const [loading, setLoading] = useState(true);
  const { pathname } = useLocation();
  useLayoutEffect(() => {
    setLoading(true);
    const timer = setTimeout(() => {
      setLoading(false);
    }, 2500);
    return () => clearTimeout(timer);
  }, [pathname]);
  return loading ? <Spinner /> : <RoutesWrapper />;
}

导出默认应用程序;

相关问题