升级RNN v2后调用Navigation.push报错,求技术排查指导
我看到你升级到RNN v2后遇到了undefined is not an object (evaluating '_reactNativeNavigation.default.push')的错误,结合你的代码分析,主要问题出在Navigation的导入方式,同时帮你理清componentId和栈id的疑问:
1. 修复Navigation导入错误
在你的Landing.js中,你使用了默认导入import Navigation from 'react-native-navigation';,但RNN v2中Navigation是命名导出而非默认导出。这种错误的导入方式会导致Navigation变量为undefined,自然调用push方法会触发报错。
修改Landing.js的导入语句:
// 错误写法 import Navigation from 'react-native-navigation'; // 正确写法 import { Navigation } from 'react-native-navigation';
2. 关于componentId的疑问
你担心this.props.componentId的有效性,其实RNN v2会自动将componentId注入到所有注册过的屏幕组件的props中,完全不需要你手动传递。你可以在Landing组件的componentDidMount里加个日志验证:
componentDidMount() { console.log('当前屏幕的componentId:', this.props.componentId); }
如果能输出一串类似ComponentId-1的字符串,说明componentId已经正确传递了。
3. 栈id和屏幕id的使用说明
- 你在
App.js中设置的栈idappStack,是用来全局操作整个栈的(比如调用Navigation.popToRoot('appStack')直接回到栈底),日常的push/pop操作只需要当前屏幕的componentId,RNN会自动找到它所在的栈。 - 每个屏幕的
componentId是RNN自动生成的,不需要你手动给屏幕设置id,注册组件时只需要指定name即可,RNN会在创建屏幕实例时自动分配唯一的componentId。
修改后的Landing.js示例
import React, { Component } from 'react'; import { View, Button } from 'react-native'; // 修正导入方式 import { Navigation } from 'react-native-navigation'; import strings from '../../global/strings'; class Landing extends Component { goToScreen = (screenName) => { // 用this.props.componentId调用push Navigation.push(this.props.componentId, { component: { name: screenName, options: { topBar: { title: { text: "Auth Screen" } } } } }) } componentDidMount() { // 验证componentId是否存在 console.log('Landing Screen componentId:', this.props.componentId); } render() { return ( <View> <Button title="Connexion" onPress={() => this.goToScreen(strings.screens.screenAuth)} /> </View> ) } } export default Landing;
先修改导入方式,应该就能解决你当前的报错了。如果还是有问题,检查日志里是否能看到componentId,或者确认你的Redux包装是否正确(registerComponentWithRedux已经帮你处理了props传递,一般不会有问题)。
内容的提问来源于stack exchange,提问作者Studio Espaces Temps
相关产品推荐
相关产品推荐

