← 中文资源

简体中文版本

SPA 路由的类型化 history state

用类型化 history state 做 SPA 路由:pushState 写入带类型的载荷,popstate 读回时判空兜底,刷新后 state 为 null。

阅读英文原文

实现说明

底层就是函数 navigate。

使用要点

  • 浏览器才是这里的运行环境:window 在 Node 里拿不到。
  • 每一步打印都带着自己的标签:route:、current page:。

常见问题

「SPA 路由的类型化 history state」能在裸 Node.js 里跑吗?

不能——window 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

签名一览:function navigate(state: RouteState, url: string)

核心语句

window.addEventListener('popstate', (event: PopStateEvent) => {
  const state = event.state as RouteState | null;
  console.log('route:', state ? state.page : 'unknown');
});

代码示例

type RouteState = { page: 'home' | 'settings'; userId?: string };

function navigate(state: RouteState, url: string): void {
  // 状态对象与 URL 一同写入历史栈(route 语义)
  history.pushState(state, '', url);
}

window.addEventListener('popstate', (event: PopStateEvent) => {
  const state = event.state as RouteState | null;
  console.log('route:', state ? state.page : 'unknown');
});

navigate({ page: 'home' }, '/');
navigate({ page: 'settings', userId: 'u_7' }, '/settings/u_7');
console.log('current page:', (history.state as RouteState).page);