在反应路由器中显示路由之间的简单加载指示符

时间:2017-11-03 20:50:31

标签: javascript reactjs redux react-redux react-router

我来自 AngularJS 世界并且几天前开始用react-router编写我的第一个React App,在 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 App中我有:

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 个答案:

答案 0 :(得分:4)

您可以使用高阶组件做出反应,以通用方式执行此操作。

看一个例子:

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

答案 1 :(得分:0)

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

只需使用此包中的 SwitchRoute 而不是 react-router-dom

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

loading 道具添加到您要等待的路线:

<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();
};