我来自 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吗?
答案 0 :(得分:4)
答案 1 :(得分:0)
如果你获取一些数据,我做了一个小包 react-router-loading,它允许你显示加载指示器并在切换屏幕之前加载一些数据。
只需使用此包中的 Switch
和 Route
而不是 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();
};