更改Facebook等网站上的页面会触发浏览器的加载指示,尽管有时可能不会进行整页重新加载。如何使用React实现类似的行为?
答案 0 :(得分:0)
如果您正在使用react-router,您可以在客户端本身处理路由更改。您可以创建HOC以在路线更改时显示加载指示器。
import React from 'react';
import Loader from './Loader';
function withRouteLoader(WrappedComponent) {
class AppWithRouteLoader extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
loadedRoutes: props.location && [props.location.pathname],
};
this.updateIsLoading = this.updateIsLoading.bind(this);
}
componentWillMount() {
this.unsubscribeHistory = this.props.router && this.props.router.listenBefore((location) => {
if (this.state.loadedRoutes.indexOf(location.pathname) === -1) {
this.updateIsLoading(true);
}
});
}
componentWillUpdate(newProps, newState) {
const { loadedRoutes } = this.state;
const { pathname } = newProps.location;
if (loadedRoutes.indexOf(pathname) === -1 && newState.isLoading === true) {
this.updateIsLoading(false);
this.setState({
loadedRoutes: loadedRoutes.concat([pathname]),
});
}
}
componentWillUnmount() {
this.unsubscribeHistory = undefined;
}
updateIsLoading(isLoading) {
this.setState({ isLoading });
}
render() {
return (
<div>
<Loader show={this.state.isLoading} />
<WrappedComponent {...this.props} />
</div>
);
}
}
AppWithRouteLoader.propTypes = {
location: React.PropTypes.object,
router: React.PropTypes.object,
};
return AppWithRouteLoader;
}
export default withRouteLoader;
你可以参考这个Boilterplate https://github.com/react-boilerplate/react-boilerplate。它实现了整个事情