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

React Native中StackNavigator传Props及页面回退问题咨询

React Native + React Navigation + Redux 问题解答

代码片段

import React, {Component} from 'react' 
import { StackNavigator } from 'react-navigation' 
import {connect} from 'react-redux' 
import {getAllUsers} from '../actions' 
import {List, ListItem} from 'react-native-elements' 
import { StyleSheet, Text, View, FlatList } from 'react-native' 

const UserDetail = () => { <View> <Text>User Detail</Text> </View> } 

const Home = ({ navigation }) => ( <List> {typeof users === 'string' && <FlatList data={users} /> } </List> ) 

const Stack = StackNavigator({ 
  Home: { screen: Home }, 
  UserDetail: { screen: UserDetail } 
}) 

class MainScreen extends Component { 
  componentDidMount(){ 
    this.setState({ users : this.props.getAllUsers() }) 
  } 
  render() { 
    const users = typeof this.props.decks === 'string' ? Object.values(JSON.parse(this.props.users)) : '' 
    return( <Stack /> ) 
  } 
} 

function mapStateToProps(users) { 
  return { users: users, } 
} 

function mapDispatchToProps(dispatch) { 
  return { getAllUsers: () => dispatch(getAllUsers()), } 
} 

export default connect( mapStateToProps, mapDispatchToProps )(MainScreen)

技术问询

  • 我需要将MainScreen组件中的users props传递给Home组件,后续还要传递给UserDetail组件,但查阅React Navigation文档后仅找到ScreenProps相关示例,恳请指导可行方案。
  • 跳转到独立组件UserDetail且该组件调用其他组件后,如何实现回退到Home页面?我使用Redux尝试回退但未成功,作为React/Native新手,希望得到明确解决方法。

问题解答

Hey there! Let's break down your two questions step by step, with fixes and improvements to your existing code:

1. 传递users给Home和UserDetail组件

你有两种靠谱的方案,根据你的需求选择:

方案一:使用React Navigation的screenProps(适配当前代码结构)

先修正MainScreen里的错误逻辑,再传递props:

// 修正componentDidMount:不需要setState,直接调用action获取用户
componentDidMount(){
  this.props.getAllUsers() // 调用action后,Redux会自动更新组件props
}

render() {
  // 修正变量名错误:是this.props.users不是this.props.decks,同时默认值设为数组更合理
  const users = typeof this.props.users === 'string' ? Object.values(JSON.parse(this.props.users)) : []
  // 通过screenProps把users传给Stack里的所有页面
  return( <Stack screenProps={{ users: users }} /> )
}

然后更新Home组件,通过screenProps拿到users并添加跳转逻辑:

const Home = ({ navigation, screenProps }) => (
  <List>
    {/* 修正判断逻辑:确保users是数组且有数据再渲染 */}
    {Array.isArray(screenProps.users) && screenProps.users.length > 0 && (
      <FlatList 
        data={screenProps.users}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({item}) => (
          <ListItem 
            title={item.name} // 假设用户对象有name字段
            onPress={() => navigation.navigate('UserDetail', { user: item })} // 传递单个用户到详情页
          />
        )}
      />
    )}
  </List>
)

在UserDetail里,通过navigation参数获取传递过来的用户:

const UserDetail = ({ navigation }) => {
  // getParam的第二个参数是默认值,避免无数据时报错
  const user = navigation.getParam('user', {})
  return (
    <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
      <Text>User Detail: {user.name}</Text>
    </View>
  )
}
方案二:直接在子组件中连接Redux(更符合Redux最佳实践)

既然users已经存在Redux Store里,Home和UserDetail可以直接通过connect获取,不需要层层传递:

首先修正MainScreen的mapStateToProps(参数是Redux的全局state,不是users):

function mapStateToProps(state) { 
  const users = typeof state.users === 'string' ? Object.values(JSON.parse(state.users)) : []
  return { users } 
}

然后修改Home组件,直接从Redux拿users:

import { connect } from 'react-redux'

const Home = ({ navigation, users }) => (
  <List>
    {Array.isArray(users) && users.length > 0 && (
      <FlatList 
        data={users}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({item}) => (
          <ListItem 
            title={item.name}
            onPress={() => navigation.navigate('UserDetail', { userId: item.id })} // 传递用户ID
          />
        )}
      />
    )}
  </List>
)

// Home组件自己连接Redux获取users
function mapStateToProps(state) {
  const users = typeof state.users === 'string' ? Object.values(JSON.parse(state.users)) : []
  return { users }
}

export default connect(mapStateToProps)(Home)

UserDetail组件通过用户ID从Redux获取对应用户:

import { connect } from 'react-redux'
import { Button } from 'react-native'

const UserDetail = ({ navigation, user }) => (
  <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
    <Text>User Detail: {user.name}</Text>
    <Button title="Back to Home" onPress={() => navigation.goBack()} />
  </View>
)

function mapStateToProps(state, ownProps) {
  const userId = ownProps.navigation.getParam('userId', '')
  const users = typeof state.users === 'string' ? Object.values(JSON.parse(state.users)) : []
  const user = users.find(u => u.id === userId) || {}
  return { user }
}

export default connect(mapStateToProps)(UserDetail)

2. 回退到Home页面

新手完全不需要用Redux处理导航,React Navigation自带的navigation.goBack()就足够:

  • 在UserDetail组件里,直接通过navigation props调用goBack(),就能回到上一个页面(也就是Home):
<Button 
  title="Go Back to Home" 
  onPress={() => navigation.goBack()} 
/>
  • 如果是从UserDetail跳转到其他组件后,想直接回到Home(不是回退一步),可以用navigation.navigate('Home'):
<Button 
  title="Jump to Home" 
  onPress={() => navigation.navigate('Home')} 
/>

注意:因为UserDetail是StackNavigator中注册的页面,默认会自动接收navigation props,不需要额外配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:09:52