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

React Native导航传参报错:无法获取用户属性触发TypeError

嘿,我来帮你搞定这个跳转后拿不到用户数据的问题!你遇到的TypeError主要有两个核心原因,咱们一步步修正:

问题1:构造函数的参数和调用错误

你写的constructor(user)是不对的,React组件的构造函数默认接收的是props参数,而且必须把props传给super(),不然在构造函数里this.props会是undefined。

问题2:导航参数的位置找错了

在react-navigation里,通过navigate方法传递的参数,并不是直接挂载在组件的props根节点下,而是存在this.props.navigation.state.params里的。你直接去取this.props.user,自然会拿到undefined,进而报错。

修正后的Details.js代码

我帮你调整了代码,不仅修复了上述问题,还加了空值判断,避免组件初始化时参数未就绪的情况:

import React, {Component} from 'react';
import {AppRegistry, Text, View, Button} from 'react-native';

export default class Details extends Component{
  // 构造函数接收props并传给super
  constructor(props) {
    super(props);
    // 从navigation的state.params里取用户数据,加空值兜底
    const user = this.props.navigation.state.params?.user || {};
    this.state = {
      name: user.name || '',
      email: user.email || ''
    }
  }

  onPress(){
    this.props.navigation.navigate('Home')
  };

  render(){
    // 其实更推荐直接在render里取参数,不用存到state里(除非你需要修改这个数据)
    // const user = this.props.navigation.state.params?.user || {};
    return(
      <View>
        <Text>{this.state.name}</Text>
        <Text>{this.state.email}</Text>
        <Button onPress={this.onPress.bind(this)} title="Go Back" />
      </View>
    );
  }
}

AppRegistry.registerComponent('Details', () => Details);

额外提醒

还要确保你的StackNavigator配置里已经正确注册了Details屏幕,比如类似这样:

const MainNavigator = StackNavigator({
  Home: { screen: Component5 },
  Details: { screen: Details },
  // 其他你的屏幕...
});

这样修改后,点击列表项跳转详情页时,就能正常显示用户的姓名和邮箱啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:04