如何解决:TypeError:未定义不是对象(评估“navigation.navigate”)
2022-01-14
1309
我尝试在 React Native 中使用 Stack Navigator 从“欢迎屏幕”转到下一页“创建闹钟屏幕”,但是,它一直给我错误,即 navigation.navigate 未定义。
我在 index.js 文件中创建了一个 MyStack 函数:
const Stack = createNativeStackNavigator();
function MyStack() {
return (
<Stack.Navigator initialRouteName='WelcomeScreen'>
<Stack.Screen name="WelcomeScreen" component={WelcomeScreen} />
<Stack.Screen name="CreateAlarmScreen" component={CreateAlarmScreen} />
</Stack.Navigator>
);
}
export default MyStack;
这是我的 WelcomeScreen.js 文件:
import React, { useEffect, useState } from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Dimensions,Button, Text, View ,TouchableOpacity, Image, SafeAreaView, Component } from 'react-native';
import { backgroundColor } from 'react-native/Libraries/Components/View/ReactNativeStyleAttributes';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
function WelcomeScreen({navigation}) {
return (
<SafeAreaView style= {styles.Container}>
<View style={styles.CreateAlarmButton}>
<Button
onPress={()=>navigation.navigate('CreateAlarmScreen')}
title='Create an Alarm'
color="white"
/>
</View>
<View style={styles.ViewAlarmButton}>
<Button
title='View Alarms'
color="black"
/>
</View>
</SafeAreaView>
);
}
export default WelcomeScreen;
然后这是我的 app.js 文件:
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Dimensions, Text, View ,TouchableOpacity, Image, SafeAreaView } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import WelcomeScreen from './app/screens/WelcomeScreen';
import CreateAlarmScreen from './app/screens/CreateAlarmScreen';
import MyStack from './app/Navigation';
export default function App() {
return (
<NavigationContainer>
<MyStack/>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'peachpuff',
justifyContent: 'center',
alignItems: 'center'
},
});
我真的很困惑如何解决这个问题。
2个回答
您可以导入使用导航,然后可以声明该变量
import { useNavigation } from '@react-navigation/native';
const navigation = useNavigation();
Dicka Reynaldi
2022-01-14
navigation
通常在第一次渲染后填充,因此在填充之前它将处于未定义状态。请尝试使用
navigation?.navigate
。
Abe
2022-01-14