navigator getcurrentlocation 永远调用
navigator getcurrentlocation calls forever
为什么这个 ReactJS 代码会无限调用 navigator.geolocation.getCurrentLocation? console.log 中的 getCurrentLocation 永远被调用。这是为什么?
const [today, setTodaysWeather] = useState('');
const [{lat, lng}, setLocation] = useState({lat: 0, lng: 0});
if(!navigator.geolocation) {
console.log("gelolocation is not supported by your browser");
}
else {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude
});console.log(lat);
},
(err) => {
console.log("Error getting location");
});
}
useEffect(() => {
fetch("//api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lng + "&appid=")
.then((response) => {
return response.json();
})
.then((json) => {
setTodaysWeather(json);
})
});
您应该将此代码包装在一个效果中,因为该代码正在通过 setLocation
更改状态,这会触发另一个渲染,再次递归地运行您的代码。
useEffect(()=> {
if(!navigator.geolocation) {
console.log("gelolocation is not supported by your browser");
}
else {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude
});console.log(lat);
},
(err) => {
console.log("Error getting location");
});
}
}, [])
作为 effect 函数的第二个参数的空数组将确保此代码在组件的第一次渲染期间仅 运行 一次。
为什么这个 ReactJS 代码会无限调用 navigator.geolocation.getCurrentLocation? console.log 中的 getCurrentLocation 永远被调用。这是为什么?
const [today, setTodaysWeather] = useState('');
const [{lat, lng}, setLocation] = useState({lat: 0, lng: 0});
if(!navigator.geolocation) {
console.log("gelolocation is not supported by your browser");
}
else {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude
});console.log(lat);
},
(err) => {
console.log("Error getting location");
});
}
useEffect(() => {
fetch("//api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lng + "&appid=")
.then((response) => {
return response.json();
})
.then((json) => {
setTodaysWeather(json);
})
});
您应该将此代码包装在一个效果中,因为该代码正在通过 setLocation
更改状态,这会触发另一个渲染,再次递归地运行您的代码。
useEffect(()=> {
if(!navigator.geolocation) {
console.log("gelolocation is not supported by your browser");
}
else {
navigator.geolocation.getCurrentPosition((position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude
});console.log(lat);
},
(err) => {
console.log("Error getting location");
});
}
}, [])
作为 effect 函数的第二个参数的空数组将确保此代码在组件的第一次渲染期间仅 运行 一次。