允许位置权限后城市选择器state值无法修改是什么原因?
问题根因
你在Nearest组件顶层直接写了location && NearestCity(location.latitude, location.longitude)执行逻辑,只要组件发生重渲染(用户手动选择城市触发setLoc后,组件必然会重渲染),且已经拿到定位的location值时,就会自动调用NearestCity方法执行setLoc,把选中值覆盖为当前定位的最近城市,导致用户选择失效。
修复方案
将「根据定位设置默认城市」的逻辑放在useEffect中,仅在首次拿到定位结果、城市列表加载完成时执行一次,后续不再触发覆盖逻辑。
修改后的Nearest组件代码如下:
function Nearest({ loc, setLoc }) { const { location } = useCurrentLocation(); const { city } = useCity(); // 新增useEffect,仅在定位结果、城市列表初始化完成时执行一次 useEffect(() => { if (!location || !city?.length) return NearestCity(location.latitude, location.longitude); }, [location, city]) // Convert Degress to Radians function Deg2Rad(deg) { return (deg * Math.PI) / 180; } function PythagorasEquirectangular(lat1, lon1, lat2, lon2) { lat1 = Deg2Rad(lat1); lat2 = Deg2Rad(lat2); lon1 = Deg2Rad(lon1); lon2 = Deg2Rad(lon2); var R = 6371; // km var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2); var y = lat2 - lat1; var d = Math.sqrt(x * x + y * y) * R; return d; } function NearestCity(latitude, longitude) { var minDif = 99999; var closest; var dif; city.map((item, index) => { dif = PythagorasEquirectangular(latitude, longitude, item.lat, item.lon); if (dif < minDif) { closest = index; minDif = dif; } }); setLoc(city[closest]); } //select city const handleChange = (e) => { var index = e.target.selectedIndex; setLoc(city[index]); };
内容的提问来源于stack exchange,提问作者thegetaway
相关产品推荐
相关产品推荐

