Skip to content

Instantly share code, notes, and snippets.

@wzuo
Created March 23, 2017 13:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wzuo/e9c18132c94b5494a3156b2a2e6e57f6 to your computer and use it in GitHub Desktop.
Save wzuo/e9c18132c94b5494a3156b2a2e6e57f6 to your computer and use it in GitHub Desktop.
import { matchPath } from 'react-router';
class MainRouter extends Component {
static displayName = 'MainRouter';
static propTypes = {
store: React.PropTypes.object,
component: React.PropTypes.oneOfType([
React.PropTypes.element,
React.PropTypes.func,
])
};
render() {
const { component, store } = this.props;
const requireAuth = (state) => !isSignedIn(state) ? '/login': null;
const requireNotAuth = (state) => isSignedIn(state) ? '/' : null;
const createSelectLocationState = () => {
let prevRoutingState, prevRoutingStateJS;
return (state) => {
const routingState = state.get('routing');
if (typeof prevRoutingState === 'undefined' || !prevRoutingState.equals(routingState)) {
prevRoutingState = routingState;
prevRoutingStateJS = routingState.toJS();
}
return prevRoutingStateJS;
};
};
return (
<Router history={history}>
<App>
<CustomSwitch store={store}>
<Route path="/" exact={true} component={Index} />
<Route path="/login" component={Login} onEnter={requireNotAuth} />
<Route path="/register" component={Register} onEnter={requireNotAuth} />
<Route component={ErrorNotFound} />
</CustomSwitch>
</App>
</Router>
);
}
}
class CustomSwitch extends Switch {
render() {
const { route } = this.context.router;
const { children, store } = this.props;
const location = this.props.location || route.location;
let match, child;
let foundRedirect = false;
React.Children.forEach(children, element => {
if (!React.isValidElement(element)) return;
if (foundRedirect) return;
const { path: pathProp, exact, strict, from, onEnter } = element.props;
const path = pathProp || from;
if (match == null) {
child = element;
match = path ? matchPath(location.pathname, { path, exact, strict }) : route.match;
if (match && onEnter) {
const returnedValue = onEnter(store.getState());
if (returnedValue) {
browserHistory.push(returnedValue);
foundRedirect = true;
}
}
}
});
return match ? React.cloneElement(child, { location, computedMatch: match }) : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment