使localStorage数据持久存在的问题

时间:2020-09-09 19:33:47

标签: javascript reactjs react-hooks local-storage

我正在制作一个可跟踪您一天完成多少任务的应用程序。一旦任务完成,就相对于所有时间已完成的总任务,跟踪当日完成的平均任务数。我希望它能够保留下来,以便我可以显示它,但是当我刷新页面时,它不会保留下来。

当我控制台登录avgWednesday时,它会正确更新,但是刷新页面后,它将返回到0

它定义为:

const [avgWednesday, setAvgWednesday] = React.useState(0);

所有这些都在功能组件内,如功能app(){

函数运行以计算平均值:

function addWednesday(){
  const currWednesday = totalWednesday + 1;
  setTotalWednesday(totalWednesday + 1);
  localStorage.setItem("storedTotalWednesday", currWednesday);

  const currTotalTasks = tasksFinishedTotal + 1;
  const wedAvg = (Math.round((currWednesday / currTotalTasks)*100));
  setAvgWednesday(wedAvg); 
  localStorage.setItem("storedAvgWed", avgWednesday);   //STORING HERE 
}

使用它使它持久(出于某种原因,即使更新平均值也永远不会运行):

React.useEffect(() => {
  const savedWedAvg = JSON.parse(localStorage.getItem("storedAvgWed")) || 0;
  setAvgWednesday(savedWedAvg);
}, []);

2 个答案:

答案 0 :(得分:0)

尽管您期望[pytest] filterwarnings = ignore::UserWarning:interpret avgWednesday更新,但不会立即发生。

setAvgWednesday异步,您应该使用setAvgWednesday进行呼叫,而不是:

wedAvg

由于setAvgWednesday(wedAvg); localStorage.setItem("storedAvgWed", wedAvg); 已经计算出并且就位。

答案 1 :(得分:0)

通过@ADyson弄清楚了该函数在React中异步运行,因此我必须存储wedAvg而不是avgWednesday(var保存计算而不是值本身)。存储wedAvg会存储0,因为该函数同时运行每一行,所以存储0而不是实际的更新平均值/计算。

function addWednesday(){
  const currWednesday = totalWednesday + 1;
  setTotalWednesday(totalWednesday + 1);
  localStorage.setItem("storedTotalWednesday", currWednesday);

  const currTotalTasks = tasksFinishedTotal + 1;
  const wedAvg = (Math.round((currWednesday / currTotalTasks)*100));
  setAvgWednesday(wedAvg); 
  localStorage.setItem("storedAvgWed", wedAvg);
}