开发者问题收集

TypeError:无法读取未定义的属性“navigate”-React native

2020-03-04
2222

我正在使用 Firebase 和 react-native 来验证用户身份。我的主要文件是 App.js,我将用户发送到 Login 组件,并且我有两个组件来管理路由。Appnavigator.js 用于创建 switchNavigator,DrawerNavigator.js 用于 createDrawernavigator。身份验证后,我想将用户发送到一个内部组件(Admin)。

以下是特定页面的代码,

Login.js

export default class Login extends React.Component {

  state = {
    email:"",
    password: "",
    errorMessage: null
  }

  handleLogin = () => {
      const { email , password } = this.state;
      firebase.auth()
          .signInWithEmailAndPassword(email, password)
          .then(() => this.props.navigation.navigate('Admin'))
          .catch(error => alert(error))
    } 
  render(){
.........................


<TouchableOpacity style={styles.loginBtn}  onPress = {
          this.handleLogin
        }>

我有两个组件来管理登录活动。 DrawerNavigator.js

import Admin from '../screens/Admin.js';
import Login from '../screens/Login.js'

import menu from '../assets/drawer.png';

const DrawerNavigator = createDrawerNavigator({

    Admin: Admin,
},
{
    drawerOpenRoute: 'openDrawer',
    drawerCloseRoute: 'DrawerClose',
    drawerToggleRoute: 'DrawerToggle'
},
);

export default DrawerNavigator;

我有 AppNavigator 页面来创建 AppContainer 和 switchnavigator。

import React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';

import DrawerNavigator from './DrawerNavigator.js';
import Login from '../screens/Login.js';
import App from '../App.js';


export default createAppContainer(
    createSwitchNavigator({
        Main:DrawerNavigator,
    })
);

我在 handleLogin 函数中使用了 this.props.navigation.navigate('Admin') 在成功登录后路由用户。但是我收到错误

TypeError: Cannot read property 'navigate' of undefined

App.js 文件

import React from 'react';
import { StyleSheet, Platform, Text, View, Image, TextInput, TouchableOpacity } from 'react-native';import AppNavigator from './navigation/AppNavigator.js';
import Login from './screens/Login.js';
import AppNavigator from '../navigation/AppNavigator.js;
export default class App extends React.Component {

  render(){
  return (

    <Login />
<AppNavigator />
  );
}}
1个回答

您尚未将 Login 组件添加为 AppNavigator 的一部分:

export default createAppContainer(
    createSwitchNavigator({
        Main:DrawerNavigator,
        Auth: createStackNavigator(
          {
            Login: Login
          }
      )
    })
);
Maksym Bezruchko
2020-03-04