哈希路由

通过window.location.hash值切换相应组件

  1. import "./styles.css";
  2. import {useState} from 'react'
  3. function Login(){
  4. return (
  5. <div className='box'>登录</div>
  6. )
  7. }
  8. function Signup(){
  9. return (
  10. <div className='box'>注册</div>
  11. )
  12. }
  13. export default function App() {
  14. let originHash = window.location.hash
  15. let originState = originHash === '#signup' ? '注册' : '登录'
  16. const [state, setState] = useState(originState)
  17. let onClickLogin = ()=>{
  18. setState('登录')
  19. window.location.hash = 'login'
  20. }
  21. let onClickSignup = ()=>{
  22. setState('注册')
  23. window.location.hash = 'signup'
  24. }
  25. return (
  26. <div>
  27. <button onClick={onClickLogin}>登录</button>
  28. <button onClick={onClickSignup}>注册</button>
  29. <div>{state==='登录' ? <Login/> : <Signup/>}</div>
  30. </div>
  31. );
  32. }

代码:https://codesandbox.io/s/objective-smoke-ludfm
参考文章: https://www.cnblogs.com/canger/p/7595641.html

其他方法
改hash不会刷新页面
修改pathname会导致页面刷新,不可取

  1. window.loaction.pathname = '/signup'

history.pushState修改url,页面不会刷新, 前提是后端将所有路径都指向首页

  1. // 获取pathname
  2. let path = window.location.pathname;
  3. let originState = path === "/signup" ? "注册" : "登录";
  4. const [state, setState] = useState(originState);
  5. let onClickLogin = () => {
  6. setState("登录");
  7. // 修改pathname
  8. window.history.pushState(null, "", "/login");
  9. };
  10. let onClickSignup = () => {
  11. setState("注册");
  12. window.history.pushState(null, "", "/signup");
  13. };

https://codesandbox.io/s/red-morning-xrcjk
缺点: 如果路由无穷多个,需要逐个判断。

React-router

官方文档:https://reactrouter.com/web/guides/quick-start
安装react-router-dom

  1. import {
  2. BrowserRouter as Router,
  3. Switch,
  4. Route,
  5. Link
  6. } from "react-router-dom";
  7. function Login() {
  8. return <div className="box">登录</div>;
  9. }
  10. function Signup() {
  11. return <div className="box">注册</div>;
  12. }
  13. function Home() {
  14. return <div className="box">欢迎</div>;
  15. }
  16. export default function App() {
  17. return (
  18. <Router>
  19. <div>
  20. {/* link必须在Router标签里使用 */}
  21. <Link to="/">Home</Link>
  22. <Link to="/signup">注册</Link>
  23. <Link to="/login">登录</Link>
  24. {/* A <Switch> looks through its children <Route>s and
  25. renders the first one that matches the current URL. */}
  26. <Switch>
  27. <Route path="/signup">
  28. <Signup />
  29. </Route>
  30. <Route path="/login">
  31. <Login />
  32. </Route>
  33. <Route path="/">
  34. <Home />
  35. </Route>
  36. </Switch>
  37. </div>
  38. </Router>
  39. );
  40. }

https://codesandbox.io/s/cool-http-mbtuf