【问题标题】:Undefined is not an object React Native StackNavigatorUndefined 不是对象 React Native StackNavigator
【发布时间】:2018-06-04 22:46:07
【问题描述】:

我一直在尝试让一个简单的 React Native StackNavigation 示例应用程序正常工作,但是我一直得到一个

TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate')

我不希望应用程序在这个阶段可以导航到任何地方,只需使用应用程序栏和一些任意文本进行部署。

import React, { Component } from 'react';
import {AppRegistry, Text} from 'react-native';
import {StackNavigator} from 'react-navigation';

export default class App extends React.Component {
  static navigationOptions = {
    title: 'Home',
  };

  render() {
    const { navigate } = this.props.navigation;
    return (
        <Text> Hello World </Text>
    );
  }
}

const appScreens = StackNavigator({
  Home: {screen: App},
})

AppRegistry.registerComponent('IntervalTimer', () => appScreens);

错误报告const { navigate } = this.props.navigation; 声明。删除这一行确实允许应用程序部署,但没有我所期望的标题。

StackNavigator 是使用 NPM 安装的,并且正在正常导入到应用程序中。

发布了类似的问题,我已经尝试了他们的建议。感谢您提供的任何帮助!

【问题讨论】:

    标签: react-native react-native-android react-native-navigation stack-navigator


    【解决方案1】:

    您可以在 StackNavigator 的选项中添加 initialRouteName。试试这个。

        import React, { Component } from 'react';
        import {AppRegistry, Text} from 'react-native';
        import {StackNavigator} from 'react-navigation';
    
        class App extends React.Component {
          static navigationOptions = {
            title: 'Home',
          };
    
          render() {
            const { navigate } = this.props.navigation;
            return (
                <Text> Hello World </Text>
            );
          }
        }
    
        export const appScreens = StackNavigator({
          Home: { screen: App }
        },{
          initialRouteName: Home
        })
    
        AppRegistry.registerComponent('IntervalTimer', () => appScreens);
    

    【讨论】:

      【解决方案2】:

      如果这只是道具可能有未​​定义的可能性,您可以检查未定义。

      const { navigate } = this.props.navigation || {};
      

      假设在某个时候navigation 是在渲染中定义的,那么上面的内容应该可以安全使用。您可以尝试记录它并查看它是否始终未定义或在某个时候被定义。

      console.log(navigate)
      

      输出可能是...

      undefined
      undefined
      //defined
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-14
        • 2022-01-23
        • 2017-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多