You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native跨页面传参报错:Route未定义且不是对象

问题分析与解决

错误原因

  1. 类组件render方法的props获取错误:类组件的render()方法不接收props作为参数,你错误地在render里解构{ extraData, navigation },导致找不到对应属性引发_ref.route相关错误。
  2. 路由参数传递方式错误:extraData是React Navigation用于优化列表组件(如FlatList)的属性,不是用来给屏幕组件传递路由参数的,正确的静态参数传递应该用initialParams。
  3. 参数解构逻辑错误:就算参数传递正确,你写的extraData.initialParams也是完全错误的路径。

修正方案

方案1:使用initialParams传递静态参数(适合固定值)

修改App.js里的Stack.Screen配置,把extraData换成initialParams:

// App.js
<Stack.Screen
  name="Test"
  component={TestScreen}
  initialParams={{ measurementId: 2 }} // 替换extraData为initialParams
/>

然后修改TestScreen类组件,通过this.props获取参数:

// TestScreen.js
import React from "react";
import { Button, View, Text } from "react-native";

class TestScreen extends React.Component {
  render() {
    // 从this.props.route.params里获取参数,加可选链避免未定义报错
    const { measurementId } = this.props.route.params || {};

    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text>Test Screen</Text>
        <Text>measurementId: {measurementId}</Text>
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate("Home")}
        />
      </View>
    );
  }
}

export default TestScreen;

方案2:导航时动态传递参数(适合需要根据操作传不同值的场景)

如果需要从HomeScreen跳转到TestScreen时动态传参,修改HomeScreen的Button onPress事件:

// App.js里的HomeScreen
<Button
  title="Go to Test"
  onPress={() => {
    // 跳转时直接传递参数
    navigation.navigate("Test", { measurementId: 2 });
  }}
/>

TestScreen的代码和方案1一致,通过this.props.route.params获取参数即可,此时App.js里的Stack.Screen不需要加initialParams。

关键注意点

  • 类组件的导航相关props(navigation、route)都挂载在this.props上,函数组件才是直接解构参数。
  • React Navigation中,屏幕组件的参数统一通过route.params获取,不要用extraData做参数传递。

内容的提问来源于stack exchange,提问作者XmlShark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:10:24