修复定位问题

This commit is contained in:
张成
2025-12-06 21:39:16 +08:00
parent 12b5bb1f7f
commit 2c83d9faa5

View File

@@ -98,38 +98,42 @@ const HomeNavbar = (props: IProps) => {
}, [cityPopupVisible]);
const userInfo = useUserInfo();
const locationProvince = (userInfo as any)?.province || ""; // 定位获取的省份
// 只使用省份不使用区域city、district
// 使用用户详情接口中的 last_location 字段
// USER_SELECTED_CITY 第二个值应该是省份/直辖市,不能是区
const lastLocationProvince = (userInfo as any)?.last_location_province || "";
// 只使用省份/直辖市,不使用城市(城市可能是区)
const detectedLocation = lastLocationProvince;
// 初始化城市:优先使用缓存的定位信息,其次使用当前定位
// 初始化城市:优先使用缓存的定位信息,其次使用用户详情中的位置信息
useEffect(() => {
// 1. 尝试从缓存中读取上次的定位信息
const cachedCity = (Taro as any).getStorageSync(CITY_CACHE_KEY);
if (cachedCity && cachedCity.length === 2) {
if (cachedCity && Array.isArray(cachedCity) && cachedCity.length === 2) {
// 如果有缓存的定位信息,使用缓存
console.log("使用缓存的定位城市:", cachedCity);
updateArea(cachedCity);
const cachedCityArray = cachedCity as [string, string];
console.log("使用缓存的定位城市:", cachedCityArray);
updateArea(cachedCityArray);
// 如果当前定位省份已获取且与缓存不同,弹窗询问是否切换
if (locationProvince && cachedCity[1] !== locationProvince && !hasShownLocationDialog.current) {
// 如果用户详情中有位置信息且与缓存不同,弹窗询问是否切换
if (detectedLocation && cachedCityArray[1] !== detectedLocation && !hasShownLocationDialog.current) {
hasShownLocationDialog.current = true;
showLocationConfirmDialog(locationProvince, cachedCity);
showLocationConfirmDialog(detectedLocation, cachedCityArray);
}
} else if (locationProvince) {
// 如果没有缓存但有定位信息,直接使用定位并保存到缓存
console.log("没有缓存,使用当前定位省份:", locationProvince);
const newArea: [string, string] = ["中国", locationProvince];
} else if (detectedLocation) {
// 如果没有缓存但有用户详情中的位置信息,直接使用并保存到缓存
console.log("没有缓存,使用用户详情中的位置信息:", detectedLocation);
const newArea: [string, string] = ["中国", detectedLocation];
updateArea(newArea);
// 保存定位信息到缓存
(Taro as any).setStorageSync(CITY_CACHE_KEY, newArea);
}
}, [locationProvince]);
}, [detectedLocation]);
// 显示定位确认弹窗
const showLocationConfirmDialog = (detectedProvince: string, cachedCity: [string, string]) => {
const showLocationConfirmDialog = (detectedLocation: string, cachedCity: [string, string]) => {
console.log('[LocationDialog] 准备显示定位确认弹窗,隐藏 GuideBar');
setLocationDialogData({ detectedProvince, cachedCity });
setLocationDialogData({ detectedProvince: detectedLocation, cachedCity });
setLocationDialogVisible(true);
// 显示弹窗时隐藏 GuideBar
setShowGuideBar(false);
@@ -141,12 +145,12 @@ const HomeNavbar = (props: IProps) => {
if (!locationDialogData) return;
const { detectedProvince } = locationDialogData;
// 用户选择"是",切换到当前定位城市
// 用户选择"切换到",使用用户详情中的位置信息
const newArea: [string, string] = ["中国", detectedProvince];
updateArea(newArea);
// 更新缓存为新的定位信息(只有定位的才缓存)
// 更新缓存为新的定位信息
(Taro as any).setStorageSync(CITY_CACHE_KEY, newArea);
console.log("切换到当前定位城市并更新缓存:", detectedProvince);
console.log("切换到用户详情中的位置信息并更新缓存:", detectedProvince);
// 关闭弹窗
setLocationDialogVisible(false);