Ionic React中根据Swiper活跃滑块获取MongoDB关联地址数据
实现方案
1. 新增必要状态
先在组件内新增以下状态,用来存储滑块激活状态、当前选中的国家ID和地址数据:
import { ObjectId } from 'bson'; // 确保已引入ObjectId依赖 // 原有状态保留 const [country, setCountry] = useState([]); const [loadingCountry, setLoadingCountry] = useState(true); // 新增状态 const [activeSlideIndex, setActiveSlideIndex] = useState(0); const [activeCountryId, setActiveCountryId] = useState(null); const [addressList, setAddressList] = useState([]); const [loadingAddress, setLoadingAddress] = useState(false);
2. 绑定Swiper滑动切换事件
给Swiper组件添加onSlideChange回调,滑动时同步当前激活的滑块索引:
<Swiper onSlideChange={(swiper) => { setActiveSlideIndex(swiper.activeIndex); }} {/* 保留你原有Swiper的其他配置,比如分页、自动轮播等 */} > {/* 原有国家滑块渲染逻辑不变 */} {country.map((item) => ( <SwiperSlide key={item._id.toString()}> {/* 国家展示内容 */} </SwiperSlide> ))} </Swiper>
3. 同步当前激活的国家ID
新增useEffect监听滑块索引和国家列表的变化,自动更新当前选中的国家ID:
useEffect(() => { if (country.length > 0 && activeSlideIndex < country.length) { setActiveCountryId(country[activeSlideIndex]._id); } }, [activeSlideIndex, country]);
4. 监听国家ID变化拉取对应地址
新增useEffect,每次选中的国家ID变化时,重新查询关联的地址数据,注意Address集合的关联字段是大写开头的CountryId,你之前写的小写countryId会匹配不到数据:
useEffect(() => { // 无有效国家ID时不发起查询 if (!activeCountryId) return; async function fetchAddress() { setLoadingAddress(true); const client = app.currentUser?.mongoClient("mongodb-atlas"); const collection = client?.db("database").collection("address"); const res = await collection?.find({ CountryId: new ObjectId(activeCountryId.toString()), userId: new ObjectId(app.currentUser?.id) }); setAddressList(res || []); setLoadingAddress(false); } fetchAddress(); }, [activeCountryId]);
5. 渲染地址列表
在IonCard中渲染查询到的地址列表即可,可搭配加载状态优化体验:
<IonCard> <IonCardContent> {loadingAddress ? ( <p>地址加载中...</p> ) : addressList.length === 0 ? ( <p>该国家暂无关联地址</p> ) : ( addressList.map((addr) => ( <div key={addr._id.toString()}> <p>{addr.city}</p> <p>{addr.address}</p> </div> )) )} </IonCardContent> </IonCard>
内容的提问来源于stack exchange,提问作者Lily Chen
相关产品推荐
相关产品推荐

