自己寫一個Router
自己寫一個 React Router
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
page: window.location.pathname // 重新整理時抓取URL render
};
window.onpopstate = () => { // 點選瀏覽器上一頁時
this.handleRoute(document.location.pathname, true);
}
}
handleRoute(path, pop) {
if (!pop) window.history.pushState({}, "", path);
this.setState({ page: path });
}
handlelogin() {
this.handleRoute('/mainPage');
}
render() {
switch (this.state.page) {
case '/':
case '/login':
return (
<div>Login Page</div>
)
case '/main':
return (
<div>Main Page</div>
)
default:
break;
}
}
}
export default App;Last updated