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

React Native变量传递异常求助:跳转后参数未正确显示

问题原因&解决方法

嘿,这个问题我之前也碰到过,其实是react-native-router-flux的参数传递规则搞的鬼:

你看到Chat组件里this.props.name是"chat",那根本不是你传的名字,而是你定义的路由Scene的key值(就是<Scene key="chat" ... />里的那个key)!因为react-native-router-flux并不会把你传递的参数直接挂在组件的根props上,而是存在navigation.state.params这个对象里。

具体修改步骤

1. 调整Chat.js的参数读取方式

把原来直接取this.props.name的逻辑,改成从路由参数里拿,同时保留默认值的处理:

import React from "react";
import PropTypes from "prop-types";
import { View, Text } from "react-native";

class Chat extends React.Component {
  render() {
    // 优先从路由参数取name,没有的话用默认值
    const userName = this.props.navigation.state.params?.name || this.props.name;
    return (
      <View>
        <Text> Hello {userName} </Text>
      </View>
    )
  }
}

Chat.defaultProps = { name: "John" };
Chat.propTypes = { name: PropTypes.string };

export default Chat;

2. 确认Home页面的传递逻辑没问题

你Home里的Actions.chat({ name: this.state.name })写法是对的,而且你已经确认this.state.name打印正常,所以这部分不用改。

旧版本兼容(如果你的react-native-router-flux是v3及以下)

要是你用的是比较老的版本,参数可能存在this.props.params里,那改成这样就行:

const userName = this.props.params?.name || this.props.name;

你可以先在Chat组件里console.log(this.props),看看navigation或者params对象里有没有你传的name值,这样能更直观地确认~


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:59:04