简体   繁体   English

每次刷新、localStorage、useState、useEffect 中的更新问题

[英]Problem with Update in Every Refresh, localStorage, useState, useEffect

I am trying to prevent my app to go into useEffect hook and implement what is inside within a 5 second period regardless of the situation the page is refreshed or not.我试图阻止我的应用程序 go 进入 useEffect 钩子并在 5 秒内实现里面的内容,无论页面是否刷新。

My code still only fires up the useEffect hook only on page refresh.我的代码仍然只在页面刷新时触发 useEffect 挂钩。 It does not really care whether 5 seconds passed it fires up in every page refresh and then does not do anything for an eternity unless you refresh the page again.它并不真正关心它是否在每次页面刷新时触发 5 秒,然后永远不会做任何事情,除非您再次刷新页面。 It acts like a useEffect hook with empty dependency array.它就像一个带有空依赖数组的 useEffect 钩子。

How can I achieve useEffect hook to run every 5 seconds regardless the page is refreshed or not?无论页面是否刷新,如何实现 useEffect 钩子每 5 秒运行一次? Here is my snippet.这是我的片段。

  const localVisitTime = localStorage.getItem('localVisitTime');
  const currentTime = new Date().getTime();
  const timeDifference = currentTime - localVisitTime;

  const [ visitTime, setVisitTime ] = useState(localVisitTime);

  if (localVisitTime && timeDifference <= 5000) {
    // Do nothing, wait!
  } else {
    localStorage.setItem('localVisitTime', new Date().getTime());
    setVisitTime(localVisitTime);
  }

  useEffect(() => {

    const fetchData = async () => {
      console.log('Data fetched!');
    }

    fetchData();
  }, [visitTime]);

The reason it is not firing multiple times is the check for time difference happence only once, you should use a set interval which checks every second if the time is valid and tries to set the time difference in a state, but i think its not necessary.它没有多次触发的原因是检查时差只发生一次,你应该使用一个设置的间隔来检查时间是否有效并尝试在 state 中设置时差,但我认为它没有必要.

I believe you want to maintain this 5 seconds firing even between page refreshes but if its not critical, you can always start again when the page refreshes.我相信即使在页面刷新之间你也想保持这 5 秒的触发,但如果它不重要,你总是可以在页面刷新时重新开始。 I think you should use the set interval and not worry about refreshes like this.我认为你应该使用设置的时间间隔而不用担心这样的刷新。

const fetchData = async () => {
  console.log("Data fetched!");
};

useEffect(() => {
  fetchData();
  const interval = setInterval(() => {
    fetchData();
  }, 5000);
  return () => clearInterval(interval);
}, []);

This way, the fetch data will run every 5 seconds, and will run on every refresh这样,获取数据将每 5 秒运行一次,并在每次刷新时运行

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

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