React Navigation5+Firebase集成下Deep Linking跳转Profile页参数获取咨询
解决方案
你的Linking配置里的parse写法完全正确,它的作用就是将URL路径中profile/后的字符串id自动转换为数字类型,注入到route.params.id中,不需要修改这部分配置。你需要做的是改造Profile组件的逻辑,兼容应用内跳转传全量profile和深度链接仅传id拉取数据两种场景:
- 从路由参数中同时取出
id、profile、isMine三个字段,profile存在时直接用,不存在时通过id走接口拉取全量数据 - 加加载态处理深度链接场景下的接口请求过程,同时兼容异常情况(id无效、用户不存在等)
- 如果需要在深度链接场景下判断是否是当前登录用户的主页,拉取到profile数据后和本地登录态的用户id做比对即可
改造后的Profile组件参考代码如下:
// Profile组件改造后代码 import { useEffect, useState, useCallback } from 'react'; import { View, ActivityIndicator, Alert } from 'react-native'; import auth from '@react-native-firebase/auth'; import firestore from '@react-native-firebase/firestore'; const ProfileScreen = (props) => { const { id, profile: routeProfile, isMine: routeIsMine } = props.route.params; const [profileOwner, setProfile] = useState(routeProfile); const [isMine, setIsMine] = useState(routeIsMine); const [loading, setLoading] = useState(!routeProfile); const fetchProfileById = useCallback(async (uid) => { if (!uid) { Alert.alert('错误', '用户ID无效'); props.navigation.goBack(); return; } try { const userDoc = await firestore().collection('users').doc(String(uid)).get(); if (userDoc.exists) { const userData = userDoc.data(); setProfile(userData); // 自动判断是否是当前登录用户的主页 const currentUid = auth().currentUser?.uid; setIsMine(currentUid === String(uid)); } else { Alert.alert('错误', '用户不存在'); props.navigation.goBack(); } } catch (err) { console.error('拉取用户信息失败', err); Alert.alert('错误', '拉取用户信息失败,请稍后重试'); } finally { setLoading(false); } }, [props.navigation]); useEffect(() => { // 只有路由参数里没有profile的时候才走接口拉取 if (!routeProfile && id) { fetchProfileById(id); } }, [routeProfile, id, fetchProfileById]); if (loading) { return <ActivityIndicator size="large" style={{ flex: 1, justifyContent: 'center' }} />; } // 此处保留你原来的页面渲染逻辑 // ... }
完成后可直接测试深度链接跳转:
- 安卓可执行命令:
adb shell am start -W -a android.intent.action.VIEW -d "myapp://app/profile/你的测试用户id" 你的应用包名 - iOS可直接在Safari地址栏输入
myapp://app/profile/你的测试用户id触发跳转
内容的提问来源于stack exchange,提问作者Pra3t0r5
相关产品推荐
相关产品推荐

