刷新后 History API 状态丢失
快速摘要
你把数据存入 pushState——刷新后 history.state 为 null,应用丢失数据。
为什么发生
把关键应用状态仅存于 history.state
未把状态序列化到 URL 或 localStorage 作备份
误以为 pushState 能跨整页刷新保留
最小示例
✗ 错误代码
history.pushState({ filter: 'active' }, '', '/items');
// after reload: history.state is null — filter lost✓ 修复代码
history.pushState({ filter: 'active' }, '', '/items?filter=active');
// on load: const params = new URLSearchParams(location.search);
const filter = params.get('filter') || 'all';history.state 中的状态刷新后丢失。把 filter 放入 URL 查询串,应用每次加载都能从 location.search 重建。
如何诊断
刷新页面后检查 history.state——若仅在内存中则为 null
查看 URL 确认状态是否编码其中
检查应用加载时是否立即依赖 history.state
如何修复
把关键状态编码进 URL(查询参数或路径)以跨刷新保留
把状态镜像到 localStorage 或 sessionStorage 作备份
加载时从 URL 重建状态而非依赖 history.state
如何预防
把 history.state 视为临时——始终有基于 URL 的回退
使用自动把状态同步到 URL 的路由器