哈希路由
通过window.location.hash值切换相应组件
import "./styles.css";
import {useState} from 'react'
function Login(){
return (
<div className='box'>登录</div>
)
}
function Signup(){
return (
<div className='box'>注册</div>
)
}
export default function App() {
let originHash = window.location.hash
let originState = originHash === '#signup' ? '注册' : '登录'
const [state, setState] = useState(originState)
let onClickLogin = ()=>{
setState('登录')
window.location.hash = 'login'
}
let onClickSignup = ()=>{
setState('注册')
window.location.hash = 'signup'
}
return (
<div>
<button onClick={onClickLogin}>登录</button>
<button onClick={onClickSignup}>注册</button>
<div>{state==='登录' ? <Login/> : <Signup/>}</div>
</div>
);
}
代码:https://codesandbox.io/s/objective-smoke-ludfm
参考文章: https://www.cnblogs.com/canger/p/7595641.html
其他方法
改hash不会刷新页面
修改pathname会导致页面刷新,不可取
window.loaction.pathname = '/signup'
用history.pushState修改url,页面不会刷新, 前提是后端将所有路径都指向首页
// 获取pathname
let path = window.location.pathname;
let originState = path === "/signup" ? "注册" : "登录";
const [state, setState] = useState(originState);
let onClickLogin = () => {
setState("登录");
// 修改pathname
window.history.pushState(null, "", "/login");
};
let onClickSignup = () => {
setState("注册");
window.history.pushState(null, "", "/signup");
};
https://codesandbox.io/s/red-morning-xrcjk
缺点: 如果路由无穷多个,需要逐个判断。
React-router
官方文档:https://reactrouter.com/web/guides/quick-start
安装react-router-dom
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
function Login() {
return <div className="box">登录</div>;
}
function Signup() {
return <div className="box">注册</div>;
}
function Home() {
return <div className="box">欢迎</div>;
}
export default function App() {
return (
<Router>
<div>
{/* link必须在Router标签里使用 */}
<Link to="/">Home</Link>
<Link to="/signup">注册</Link>
<Link to="/login">登录</Link>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/signup">
<Signup />
</Route>
<Route path="/login">
<Login />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}