Page({ data: { userInfo:null, spotId: null, spots: [], reviews: [], markers: [], spot: {} }, onLoad(options) { const spotId = options.id; this.setData({ spotId }); // 使用 setData 更新数据,而不是直接修改 this.data console.log('当前 spotId:', this.data.spotId); wx.request({ url: 'http://127.0.0.1:8000/api/red-spots-search/', method: 'GET', success: (res) => { console.log('API 返回数据:', res.data); this.setData({ spots: res.data }); // 更新 spots 数据 this.loadSpotDetail(); // 加载详情 }, fail: (err) => { console.error('请求失败:', err); } }); this.checkLoginStatus(); }, checkLoginStatus() { const userInfo = wx.getStorageSync('userInfo'); if (userInfo) { this.setData({ userInfo }); } }, addToPlan() { if (!this.data.userInfo) { wx.showToast({ title: '请先登录', icon: 'none', duration: 2000, success: () => { setTimeout(() => { wx.navigateTo({ url: '/pages/login/login' }); }, 2000); } }); return; } // 已登录用户的逻辑 this.addSpotToUserPlan(); }, addSpotToUserPlan() { const userInfo = wx.getStorageSync('userInfo'); const spot = this.data.spot; wx.showLoading({ title: '正在加入行程...' }); wx.request({ url: 'http://127.0.0.1:8000/api/add-to-plan/', method: 'POST', header: { 'Content-Type': 'application/json' }, data: JSON.stringify({ user_id: userInfo.id, spot_id: spot.id, spot_name: spot.name, spot_img: spot.image_url }), success: (res) => { wx.hideLoading(); if (res.statusCode === 201) { wx.showToast({ title: '已加入行程', icon: 'success' }); setTimeout(() => { wx.redirectTo({ url: '/pages/daohang/daohang', fail: () => wx.switchTab({ url: '/pages/daohang/daohang' }) // 备用跳转 }); }, 1500); } else { wx.showToast({ title: res.data.message || '操作失败', icon: 'none' }); } }, fail: (err) => { wx.hideLoading(); wx.showToast({ title: '网络错误,请重试', icon: 'none' }); } }); }, // 加载景点详情 loadSpotDetail() { const { spots, spotId } = this.data; // 从 data 中解构 spots 和 spotId // 检查 spots 是否存在,并且 spotId 是有效的 if (!spots || !spotId) { console.error('spots 数据未加载或 spotId 无效'); return; } // 查找匹配的景点 const spot = spots.find(item => item.id == spotId); // 使用 == 因为 spotId 可能是字符串 if (spot) { console.log('找到景点:', spot); this.setData({ spot }); // 更新 spot 数据 } else { console.error('未找到对应景点'); } }, });