You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中localStorage值重渲染后反复变回0的问题排查

问题排查与修复方案

1. 核心问题定位

你遇到的问题本质是组件初始化时没有从localStorage读取已保存的最优值,而是直接用0作为初始状态,导致每次刷新或重渲染都会覆盖掉localStorage里的有效数据。

2. 修复初始化逻辑

修改状态初始化代码,在组件挂载时优先读取localStorage中的值,不存在时才用0作为默认值:

// 读取本地存储的最优掷骰次数,无数据则返回0
const getInitialBestRolls = () => {
  const saved = localStorage.getItem('bestRolls');
  return saved ? parseInt(saved) : 0;
};

// 读取本地存储的最优耗时,无数据则返回0
const getInitialBestTime = () => {
  const saved = localStorage.getItem('bestTime');
  return saved ? parseInt(saved) : 0;
};

// 用上述函数初始化状态
const [bestRollCount, setBestRollCount] = useState(getInitialBestRolls());
const [bestTime, setBestTime] = useState(getInitialBestTime());

3. 验证游戏结束的存储逻辑

确保游戏结束时的对比更新逻辑正确,避免把初始0值当成有效最优值:

const handleGameEnd = () => {
  const currentRolls = rollCount;
  const currentTime = elapsedTime;

  // 更新最优掷骰次数
  if (bestRollCount === 0 || currentRolls < bestRollCount) {
    setBestRollCount(currentRolls);
    localStorage.setItem('bestRolls', currentRolls.toString());
  }

  // 更新最优耗时
  if (bestTime === 0 || currentTime < bestTime) {
    setBestTime(currentTime);
    localStorage.setItem('bestTime', currentTime.toString());
  }
};

4. 额外检查项

  • 确认localStorage的键名完全一致(大小写敏感,别出现bestrolls和bestRolls混用的情况)
  • 可以通过浏览器开发者工具的Application > Local Storage面板,实时查看值的写入和读取是否正常
  • 避免在组件顶层渲染逻辑中意外重置状态或localStorage值

内容的提问来源于stack exchange,提问作者user20984108

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:05:22