AllenYuan

auth - add redirect to app

Apr 24th, 2020
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Child components
  2. import Header from './Header';
  3.  
  4. // modules for a redux-connected React component
  5. import React from 'react';
  6. import { connect } from 'react-redux';
  7.  
  8. // extract appName from state
  9. const mapStateToProps = state => ({
  10.   appName: state.appName,
  11.   redirectTo: state.common.redirectTo
  12. });
  13.  
  14. const mapDispatchToProps = dispatch => ({
  15.   onRedirect: () =>
  16.     dispatch({ type: 'REDIRECT' })
  17. });
  18.  
  19. // render the appname
  20. class App extends React.Component {
  21.   // handle redirect if necessary
  22.   componentWillReceiveProps(nextProps) {
  23.     // need to redirect
  24.     if (nextProps.redirectTo) {
  25.       // redirect to given route
  26.       this.context.router.replace(nextProps.redirectTo);
  27.       // update redirectTo in state
  28.       this.props.onRedirect();
  29.     }
  30.   }
  31.  
  32.   render() {
  33.     return (
  34.       // render Header and children from router below that
  35.       <div>
  36.         <Header appName={this.props.appName} />
  37.         {this.props.children}
  38.       </div>
  39.     );
  40.   }
  41. }
  42.  
  43. // ensure react-router attaches children to this component's props
  44. App.contextTypes = {
  45.   router: React.PropTypes.object.isRequired
  46. };
  47.  
  48. // export redux-connected App
  49. export default connect(mapStateToProps, mapDispatchToProps)(App);
Advertisement
Add Comment
Please, Sign In to add comment