React Navigation中StackNavigator报错undefined is not a function,求解决方案
Hey there, let's break down why you're hitting this error and fix it step by step:
What's Causing the Issue?
You've got two main problems here:
- Wrong Import for Stack Navigator: In React Navigation 3.x,
StackNavigatorisn't part of the corereact-navigationpackage anymore—it's moved to a separate package calledreact-navigation-stack. Importing it directly fromreact-navigationgives youundefined, hence the "not a function" error. - Typos in Component Names: Your
index.jsis trying to useContactsStacksbut your router exportsContactsStack—that's a misspelling that'll break things too.
Step-by-Step Fixes
1. Install the Missing Dependency
First, you need to add the react-navigation-stack package which contains the stack navigator:
npm install react-navigation-stack --save # Or if you use Yarn: yarn add react-navigation-stack
2. Update Your route.js File
We need to adjust the imports and wrap the navigator in a container (required in React Navigation 3.x):
// route.js import { createStackNavigator } from 'react-navigation-stack'; // Use createStackNavigator from the correct package import { createAppContainer } from 'react-navigation'; // Required to wrap the navigator import Contacts from '../screens/Contacts'; import Details from '../screens/Details'; const ContactsStack = createStackNavigator({ Contacts: { screen: Contacts, navigationOptions: { title: 'Contacts', }, }, Details: { screen: Details, navigationOptions: { title: 'Details', }, }, }); // Wrap the navigator in createAppContainer and export it export default createAppContainer(ContactsStack);
3. Fix the Typo in index.js
You had a typo with ContactsStacks—change it to match the exported ContactsStack, and adjust the import since we're now using a default export:
// index.js import React from 'react'; import ContactsStack from './config/router'; // No curly braces, and correct component name const App = () => { return <ContactsStack />; }; export default App;
4. Clean Cache and Restart
Sometimes cached files can cause issues after dependency changes. Run these commands to make sure everything loads fresh:
# Clear npm cache npm cache clean --force # Restart Metro Bundler with cache reset npx react-native start --reset-cache # Re-run your app npx react-native run-android # Or run-ios if you're on iOS
Quick Context
React Navigation split its navigators into separate packages starting in version 3.x to keep the core library lightweight. So while older versions let you import StackNavigator directly from react-navigation, 3.x+ requires you to use the specific package for each navigator type (like react-navigation-stack for stack navigators, react-navigation-tabs for tab navigators).
That should get your navigation up and running without the error!
内容的提问来源于stack exchange,提问作者Abdul Hanan

