问题描述
我使用 React Native v0.63+ 和 React Navigation 5 与 Firebase 集成。我必须解决两个问题,这些问题涉及到应用程序某些部分的深层链接,为了呈现视图,需要一些包含 props.route.params
的对象,例如 profile
,这些对象可能包含也可能不包含合理的数据放入纯文本网址。
为了导航到某个配置文件而不将整个配置文件字符串化为一个无休止的 url,我认为我可以将 id
解析为必须从 api 获取的 profile
以便由视图渲染。但是我误解了 react-navigation
parse
功能。
但是,我无法找出正确的方法。我该怎么做?
这是我的 linking
对象:
export const linking = {
prefixes: ['myapp://'],config: {
Login: 'login',Signup: 'signup',PersonalInfo: 'personalinfo',Drawer: {
path: "app",screens: {
Saved: "saved",Details: "details",Trend: "trend",Profile: {
path: "profile/:id?",parse: {
id: Number,// <-- this is my profile id param
},},EditProfile: "editprofile",Multimedia: "multimedia",Premium: "premium",Chat: "chat",LikeView: "likes",ReseedView: "reseeds",Tabs: {
path: "tabs",exact: true,screens: {
Main: "main",Escribir: "escribir",Notificaciones: "notificaciones",Mensajes: "mensajes"
}
},
这就是应用程序已经处理传入的 profile
以呈现它的方式:
//from any component within navigation reach
navigation.push('Profile',{profile,ismine});
//Profile component
const ProfileScreen = (props) => {
const { profile,ismine } = props.route.params;
const [profileOwner,setProfile] = useState(profile);
//...
解决方法
始终使用参数的更好方法是使用解构 props 对象。这是 JavaScript 对象的默认 ES6 语法。
For Ex :
const { isMine } = props.route.params;
因此,我建议您遵循这种方法来解构和使用您的对象,甚至在您的组件内部进行初始化或操作,而不是直接访问整个 param 对象,例如 "props.route.params.profile"