You need to pass [] as the second parameter of useEffect
. Then, it will work like componentDidMount()
in the class component. Unless, it will be called every time the state's updated, and will occur infinite loops.
navigator.geolocation ? let posObj = {positionAllowed: false} : let posObj = {positionAllowed: true};
const [settings, setSettings] = useState(posObj);
useEffect(() => {
if(settings.positionAllowed&&navigator.geolocation){
let geolocation = navigator.geolocation.watchPosition((rawPosition)=>{
let positionData = {
positionAvailable: true,
data: rawPosition
}
if(positionData!=position){
setPosition(positionData);
}
},(err)=>{
console.log(err);
},{
enableHighAccuracy: true,
maximumAge: 10000
});
}
}
}, []); // <---------------------------------
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…