HashHistory 和 BrowserHistory:
hashHistory,浏览器上看到的 url 会是这样的: /#/user?name=zhangsan
browserHistory,浏览器上看到的 url 会是这样的:/user
https://www.jianshu.com/p/7237bf23db6a
代码学习:
实现react router的功能。
import React, {Component} from 'react';
import PropTypes from 'prop-types';
class Router extends Component {
constructor(props){
super(props);
this.state = {
hash: window.location.hash
};
}
static childContextTypes = {
hash: PropTypes.string
}
getHash(){
let url = window.location.hash.replace('#','');
return url;
}
getChildContext(){
return {
hash: this.getHash()
};
}
componentDidMount() {
window.onhashchange = () => {
this.setState({
hash: this.getHash()
});
};
}
render(){
return (<>{this.props.children}</>);
}
}
class Route extends Component {
static contextTypes = {
hash: PropTypes.string
}
render(){
const { path, component } = this.props;
let instance = null;
const {hash} = this.context;
if(path === hash) {
instance = React.createElement(component, null, null);
}
return (<>{instance}</>);
}
}
class AA extends Component {
render() {
return (<div>
AA
</div>);
}
}
class BB extends Component {
render() {
return (<div>
BB
</div>);
}
}
class App extends Component {
render() {
return (<div>
<Router>
<header>
<div>Header</div>
<Route path='/aa' component={AA}/>
<Route path='/bb' component={BB}/>
</header>
</Router>
</div>);
}
}
export default App;