简体   繁体   English

问题让 localStorage 数据持久化

[英]Issue getting localStorage data to persist

I am making an app that tracks how many tasks you complete in a day.我正在制作一个应用程序来跟踪你一天完成了多少任务。 Once a task is completed the average number of tasks completed on that day is tracked relative to the total tasks completed all time.完成任务后,会跟踪当天完成的平均任务数与所有时间完成的任务总数。 I want this to persist so I can display it but when I refresh the page it is not persisting.我希望它能够持久化以便我可以显示它,但是当我刷新页面时它不会持久化。

When I console log the avgWednesday it updates correctly but once I refresh the page it goes back to 0 .当我控制台记录avgWednesday它会正确更新,但是一旦我刷新页面,它就会返回0

It is defined as:它被定义为:

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

This is all within a functional component as function app(){这一切都在一个功能组件中,如 function app(){

Function runs to calculate the average:函数运行以计算平均值:

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 
}

Using this to make it persist (for some reason never runs even when the average is updated):使用它来使其持久化(由于某种原因,即使更新了平均值也不会运行):

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

Although you are expecting for avgWednesday to be updated by setAvgWednesday but it's not happening immediately.虽然您期望avgWednesdaysetAvgWednesday更新,但它不会立即发生。

The setAvgWednesday is asynchronous , you should call with wedAvg instead as: setAvgWednesday异步的,您应该使用wedAvg调用,如下所示:

setAvgWednesday(wedAvg); 
localStorage.setItem("storedAvgWed", wedAvg);

As wedAvg has been already calculated and it's in place.因为已经计算了wedAvg并且它已经就位。

Figured it out thanks to @ADyson the function runs asynchronously in React so I have to store wedAvg rather than avgWednesday (var holding the calculation rather than the value itself).感谢@ADyson,该函数在 React 中异步运行,所以我必须存储 wedAvg 而不是 avgWednesday(var 保存计算而不是值本身)。 Storing wedAvg would store 0 since the function runs every line at the same time, storing 0 rather than the actual updated average / calculation.存储 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM