@vve/react-router
Version:
react router for react-helper & with keep-alive
84 lines (82 loc) • 2.26 kB
JavaScript
import React from 'react';
import PropTypes from 'prop-types';
import RouterContext from "./router-context";
var noop = a => a;
/**
* The public API for putting history on context.
*/
class Router extends React.Component {
static computeRootMatch(pathname) {
return {
path: '/',
url: '/',
params: {},
isExact: pathname === '/'
};
}
constructor(props) {
super(props);
this.state = {
location: props.history.location
};
// This is a bit of a hack. We have to start listening for location
// changes here in the constructor in case there are any <Redirect>s
// on the initial render. If there are, they will replace/push when
// they mount and since cDM fires in children before parents, we may
// get a new location before the <Router> is mounted.
this.isMountedForRouter = false;
this.pendingLocation = null;
this.unlisten = props.history.listen(location => {
if (this.isMountedForRouter) {
this.setState({
location
});
} else {
this.pendingLocation = location;
}
});
}
componentDidMount() {
this.isMountedForRouter = true;
if (this.pendingLocation) {
this.setState({
location: this.pendingLocation
});
}
}
componentWillUnmount() {
if (this.unlisten) this.unlisten();
}
render() {
var _this$props = this.props,
history = _this$props.history,
children = _this$props.children,
genNextUrl = _this$props.genNextUrl,
linkExtendable = _this$props.linkExtendable;
var location = this.state.location;
return /*#__PURE__*/React.createElement(RouterContext.Provider, {
value: {
history,
location,
match: Router.computeRootMatch(location.pathname),
genNextUrl,
linkExtendable
}
}, children || null);
}
}
Router.defaultProps = {
genNextUrl: noop,
linkExtendable: false
};
Router.propTypes = {
children: PropTypes.element.isRequired,
genNextUrl: PropTypes.func,
linkExtendable: PropTypes.bool,
history: PropTypes.shape({
location: PropTypes.shape({}),
listen: PropTypes.func.isRequired
}).isRequired
};
export default Router;
//# sourceMappingURL=router.js.map