React Navigation v5屏幕埋点中routeNameRef的正确Typescript类型是什么
routeNameRef正确Typescript定义及报错修复方案
首先直接给出routeNameRef的正确类型:它存储的是路由名称字符串,初始值为undefined,所以定义为:
const routeNameRef = useRef<string | undefined>();
如果你的项目提前定义了全局路由类型RootParamList,可以用更精确的类型获得语法提示:
const routeNameRef = useRef<keyof RootParamList | undefined>();
接下来修复你遇到的TS空值报错,报错原因是两个场景下的空值未处理:
navigationRef.current在组件未完成挂载时可能为nullgetCurrentRoute()在路由状态未初始化时可能返回undefined
修改后的完整代码如下:
const Navigator = () => { const navigationRef = useRef<NavigationContainerRef>(null); // 正确类型定义 const routeNameRef = useRef<string | undefined>(); return ( <NavigationContainer ref={navigationRef} onReady={() => { const currentRoute = navigationRef.current?.getCurrentRoute(); // 空值判断后再赋值 if (currentRoute) routeNameRef.current = currentRoute.name; }} onStateChange={async () => { const previousRouteName = routeNameRef.current; const currentRoute = navigationRef.current?.getCurrentRoute(); const currentRouteName = currentRoute?.name; // 同时校验当前路由名称存在、路由发生变化再上报 if (currentRouteName && previousRouteName !== currentRouteName) { await analytics().logScreenView({ screen_name: currentRouteName, screen_class: currentRouteName, }); } if (currentRouteName) routeNameRef.current = currentRouteName; }} {/* 其余导航配置 */} > </NavigationContainer> ) }
这样处理后所有TS报错都会消失,同时也避免了运行时空值调用的风险。
内容的提问来源于stack exchange,提问作者Raphael Pinel
相关产品推荐
相关产品推荐

