我来自 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来执行此操作吗?
3条答案
按热度按时间eqfvzcg81#
你可以在react中使用高阶分量来以一般的方式完成这一点。
Look是一个例子:
https://github.com/thejameskyle/react-loadable
hpxqektj2#
如果你提取一些数据,我做了一个小包react-router-loading,它允许你在切换屏幕之前显示加载指示器并加载一些数据。
只需使用此软件包中的
Switch
和Route
,而不要使用react-router-dom
:添加
loading
prop 到你想等待的路线:然后在
About
组件中的获取逻辑的末尾添加loadingContext.done();
:a0x5cqrl3#
我认为通过使用useLayoutEffect,你可以在每一个路线变化上放置一个加载器。我任何人有问题请随时ping我。
导出默认应用程序;