React Native中如何解决“undefined is not an object (evaluating 'route.params.data')”错误?
Hey there! Let's break down this error and fix it step by step — I've been in your shoes before, so I know how frustrating this can be.
What's causing this error?
This error pops up because when you try to access route.params.data, either:
route.paramsitself is undefined (meaning no parameters were passed when navigating to HomeScreen), or- The
paramsobject exists, but it doesn't have adataproperty.
Step-by-step fixes
1. First, check where you're navigating from
Head to the code that sends the user to HomeScreen. You need to make sure you're actually passing the data parameter correctly using navigation.navigate(). Here's what a correct implementation looks like:
// Example of proper parameter passing navigation.navigate('HomeScreen', { data: yourActualDataObject // Replace this with your real data });
Double-check that yourActualDataObject isn't undefined either — if it is, you'll still run into issues even after passing it.
2. Add safety checks in HomeScreen
Don't assume route.params or route.params.data will always exist. Use these safe approaches to initialize your state:
Option 1: Use optional chaining (?.) and a default value
This is the cleanest modern approach:
const [categoryData, setCategoryData] = useState({ 0: route.params?.data || {} });
The ?. prevents the error if route.params is undefined, and || {} ensures you have a fallback empty object if data is missing.
Option 2: Explicit conditional check
If you prefer more explicit code (great for readability), do this:
// Initialize with a fallback if params are missing const initialCategoryData = route.params?.data ? { 0: route.params.data } : { 0: {} }; const [categoryData, setCategoryData] = useState(initialCategoryData);
3. Debug to confirm what's being passed
Add a console log at the top of HomeScreen to see exactly what parameters are coming through:
const HomeScreen = ({ route, navigation }) => { console.log('Received route params:', route.params); // Check your debug console for this // Rest of your code... }
This will tell you instantly if params are missing, or if the structure is different from what you expected (maybe you named it category instead of data? It happens!).
4. Nested navigation edge case (if applicable)
If you're using nested navigators (like a Stack inside a Tab), sometimes parameters might be passed to the parent navigator instead of the screen. In that case, you can access them via route.parent?.params, but this is less common — start with the first three steps first.
Final tip
Always get into the habit of adding these safety checks when accessing route parameters. React Native doesn't guarantee that parameters will exist, so defensive coding will save you a lot of headaches down the line.
内容的提问来源于stack exchange,提问作者Amos

