Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. import React, {Component} from 'react';
  2. import ReactDOM from 'react-dom';
  3. import PropTypes from 'prop-types';
  4.  
  5. export class HashRouter extends Component {
  6. constructor(props) {
  7. super(props);
  8. this.checkHash = this.checkHash.bind(this);
  9. this.selectRoute = this.selectRoute.bind(this);
  10. window.onhashchange = this.checkHash.bind(this);
  11.  
  12. this.state = {
  13. currentComponent : null,
  14. currentProps : {}
  15. };
  16. }
  17.  
  18. parseUrl(url) {
  19. var parts = url.split("#");
  20. return parts[1] || "";
  21. }
  22.  
  23. selectRoute(route) {
  24. var currentConfig;
  25.  
  26. if (route === "") {
  27. route = "empty";
  28. }
  29.  
  30. var checkRoute = typeof this.props.config[route];
  31.  
  32. if (checkRoute === 'undefined' && route === 'notfound') {
  33. // prevent resursive endless loop
  34. console.warn(`HashRouter: undefined 'notfound' route. define a notfound route in your config to handle unknown routes`);
  35. return;
  36. }
  37.  
  38. if (checkRoute === 'undefined') {
  39. currentConfig = this.selectRoute('notfound')
  40. } else if (checkRoute === 'string') {
  41. currentConfig = this.props.config[this.props.config[route]];
  42. } else if (checkRoute === 'object') {
  43. currentConfig = this.props.config[route];
  44. }
  45. return currentConfig
  46. }
  47.  
  48. checkHash(h) {
  49. var oldRoute, route;
  50. if (h) {
  51. oldRoute = this.parseUrl(h.oldURL);
  52. route = this.parseUrl(h.newURL);
  53. } else {
  54. oldRoute = "";
  55. route = document.location.hash.substring(1);
  56. }
  57.  
  58. document.body.id = route || "home";
  59. var routeInfo = this.selectRoute(route);
  60.  
  61. var newProps = Object.assign({}, routeInfo.props || {}, {
  62. prevRoute: oldRoute,
  63. route : route
  64. });
  65.  
  66. this.setState({
  67. currentComponent : routeInfo.component,
  68. currentProps : newProps
  69. });
  70. }
  71.  
  72. componentWillMount() {
  73. this.checkHash();
  74. }
  75.  
  76. render() {
  77. let ThisComp = <div />;
  78. if (this.state.currentComponent) {
  79. ThisComp = this.state.currentComponent;
  80. }
  81.  
  82. console.log(<ThisComp {...this.state.currentProps} />);
  83. return (
  84. <ThisComp {...this.state.currentProps} />
  85. )
  86. }
  87. }
  88.  
  89. HashRouter.propTypes = {
  90. config: PropTypes.object.isRequired
  91. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement