【问题标题】:Counter increment on setIntervalsetInterval 上的计数器增量
【发布时间】:2020-04-15 16:21:51
【问题描述】:
import React from 'react';
import {Plugins} from '@capacitor/core';
import {useState, useEffect} from 'react';
import {db} from './Firebase';



const Maps = () => {

const [lat, setLat] = useState(0);
const [long, setLong] = useState(0);
const [count, setCount] = useState (0);

const Counter = () => {
  setCount(count + 1)
  console.log(count)
}


const Location = () => {


      Plugins.Geolocation.getCurrentPosition().then(
        result => setLat ( result.coords.latitude)
      )

      Plugins.Geolocation.getCurrentPosition().then(
        result => setLong (result.coords.longitude)
      )
}




const interval = () => {
  setInterval (() =>
  {
    Location();
   Counter();
  }, 5000 );

}



    return (
        <div>
          <div>
            <button onClick = {interval}>
              Get Location
            </button>
             </div>
            <div>
               {long}
            </div>
              <div>
                {lat}
              </div>
        </div>
    )
}


export default Maps;

我试图通过 counter 函数让计数器在 setInterval 的每次迭代中递增,但是当我记录计数时,它不会递增并且始终保持为 0。

我尝试在 setInterval 中运行 setCount 本身但没有任何成功,它仍然不会增加计数。

【问题讨论】:

  • 你为什么使用两种不同的状态来表示位置坐标?
  • 我不知道,我试着在同样的状态下做,但我一直绊倒它,所以我选择了更简单的方法,我很确定有更好的方法来做.

标签: reactjs setinterval


【解决方案1】:

这是一个陈旧的关闭。改成这个setCount(prevCount =&gt; prevCount + 1)

使用上述设置状态的更新程序形式,您可以保证您将使用最新的状态值。

您可以将其视为函数中的count,它是声明setInterval 时其值的快照。这将使您的更新无法正常工作。

此外,设置状态是异步的,因此console.log(count) 很可能不会反映新值。登录一个效果或函数体外部,以查看每次渲染的更新值。

关于您的实施的说明: 每次单击按钮时,您都会创建一个setInterval。如果多次单击,这可能会导致一些有趣的副作用。例如,如果您单击该按钮两次,您将有两个 setIntervals 每 5 秒运行一次。

【讨论】:

  • 谢谢,它成功了。在 setInterval 按钮实现上,我真的没想到我正在测试一些逻辑,但我现在肯定会研究那个实现,谢谢。
【解决方案2】:

除了@BrianThompson 的回答。试试这个以避免不必要的重新渲染

import React from 'react';
import {Plugins} from '@capacitor/core';
import {useState, useEffect} from 'react';
import {db} from './Firebase';



const Maps = () => {

  const [state, setState] = useState({
    latLng:{lat:0,lng:0},
    counter: 0
  })
  const interval = useRef()

  //Use camelCase for methods
  const location = () => {
      Plugins.Geolocation.getCurrentPosition().then(
        result => setState ( ({counter}) => {
            counter = counter+1
            console.log(counter)
            return ({
               latLng: {
                  lat: result.coords.latitude, 
                  lng: result.coords.longitude
               },
               counter
            })
         })
      )
  }

  const startInterval = () => {
      if(interval.current) return;
      interval.current = setInterval (() => {
        location();
      }, 5000 );
   }

  const stopInterval = () ={
    clearInterval(interval.current)
    interval.current = null
  }

  useEffect(()=>{
    //Because interval is causing state updates, remember to clear interval when component will unmount
    return stopInterval    
  },[])



    return (
        <div>
          <div>
            <button onClick = {startInterval}>
              Get Location
            </button>
             </div>
            <div>
               {state.latLng.lng}
            </div>
              <div>
                {state.latLng.lat}
              </div>
        </div>
    )
}

【讨论】:

  • 谢谢,我试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多