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;
我试图通过计数器函数在setInterval的每次迭代中使计数器增加,但是当我记录计数时,它不会增加并且始终保持为0。
我尝试在setInterval内运行setCount本身,但没有成功,它仍然不会增加计数。
答案 0 :(得分:0)
它是一个过时的关闭。更改为此setCount(prevCount => prevCount + 1)
。
使用如上所述的set state的更新程序形式,可以保证您将使用state的最新值。
您可以将其视为函数中的count
,是声明setInterval
时其值的快照。这将使您的更新无法正常工作。
此外,设置状态为异步,因此console.log(count)
很可能不会反映新值。登录效果或在函数主体外部以查看每个渲染器的更新值。
关于实施的说明:
每次单击按钮时,您正在创建setInterval
。如果单击不止一次,可能会导致一些有趣的副作用。例如,如果两次单击按钮,则每5秒就会运行两个setIntervals
。
答案 1 :(得分:0)
除了@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>
)
}