HashHistory 和 BrowserHistory:
    hashHistory,浏览器上看到的 url 会是这样的: /#/user?name=zhangsan
    browserHistory,浏览器上看到的 url 会是这样的:/user

    https://www.jianshu.com/p/7237bf23db6a

    代码学习:
    实现react router的功能。

    1. import React, {Component} from 'react';
    2. import PropTypes from 'prop-types';
    3. class Router extends Component {
    4. constructor(props){
    5. super(props);
    6. this.state = {
    7. hash: window.location.hash
    8. };
    9. }
    10. static childContextTypes = {
    11. hash: PropTypes.string
    12. }
    13. getHash(){
    14. let url = window.location.hash.replace('#','');
    15. return url;
    16. }
    17. getChildContext(){
    18. return {
    19. hash: this.getHash()
    20. };
    21. }
    22. componentDidMount() {
    23. window.onhashchange = () => {
    24. this.setState({
    25. hash: this.getHash()
    26. });
    27. };
    28. }
    29. render(){
    30. return (<>{this.props.children}</>);
    31. }
    32. }
    33. class Route extends Component {
    34. static contextTypes = {
    35. hash: PropTypes.string
    36. }
    37. render(){
    38. const { path, component } = this.props;
    39. let instance = null;
    40. const {hash} = this.context;
    41. if(path === hash) {
    42. instance = React.createElement(component, null, null);
    43. }
    44. return (<>{instance}</>);
    45. }
    46. }
    47. class AA extends Component {
    48. render() {
    49. return (<div>
    50. AA
    51. </div>);
    52. }
    53. }
    54. class BB extends Component {
    55. render() {
    56. return (<div>
    57. BB
    58. </div>);
    59. }
    60. }
    61. class App extends Component {
    62. render() {
    63. return (<div>
    64. <Router>
    65. <header>
    66. <div>Header</div>
    67. <Route path='/aa' component={AA}/>
    68. <Route path='/bb' component={BB}/>
    69. </header>
    70. </Router>
    71. </div>);
    72. }
    73. }
    74. export default App;