【问题标题】:screenProps.object returns ALWAYS null in navigationOptionsscreenProps.object 在 navigationOptions 中返回 ALWAYS null
【发布时间】:2025-12-19 17:35:12
【问题描述】:

我想将获取的道具中的部分数据(用户名)放在导航标题上。请看我的navigationOptions

  static navigationOptions = ({navigation, screenProps}) => ({
    ...
    title: !_.isNil(screenProps.outfitDetail) ? 
    `${screenProps.outfitDetail.user.username}'s Post`: ''
  });

我的问题是title 总是返回一个空白字符串,因为screenProps.outfitDetail 总是为空。我在这里做错了什么?为什么总是返回null?

我在componentWillMount() 上使用 Redux 获取了 suitDetail 道具

componentWillMount() {
    const { id } = this.props.navigation.state.params;
    const { token, hType} = this.props;
    this.props.fetchOutfitDetail(token, hType, id);
  }

我可以从render() function 那里获得outfitDetail 道具。

render () {
    const detail = this.props.outfitDetail;
    if(detail) {
      return (
        <ScrollView style={styles.root}>
        ...

我通过它的 id 调用我的组件

this.props.navigation.navigate('OutfitDetail', {id})

在用户资料上做同样的事情

console.log(this.props.currentUser.username); <- prints username
this.props.navigation.navigate('Profile', {username:this.props.currentUser.username});

但在个人资料屏幕中,也无法获取screenProps.username

【问题讨论】:

  • 你在哪里传递screenProps?你在哪里设置outfitDetail?不看更多代码很难判断。
  • @Scott 感谢您的提问。我想我可以输入screenProps 来获取当前屏幕的道具。我应该把它传到某个地方吗?对于你的第二个问题,我在 mapStateToProps 上设置了装备细节。所以我可以从 render() 函数中获取对象。
  • 这真的很难调试,因为我无法在 navigationOptions 上传递 console.log() :(
  • outfitDetailfetchOutfitDetail 是否被 Redux 容器注入?
  • @Freez 是的,他们是。我认为 screenProps 没有连接到屏幕的道具。所以我想我必须把道具放在组件上。

标签: reactjs react-native react-redux react-navigation


【解决方案1】:

您无法使用screenProps 访问屏幕的组件属性。要在 navigationOptions 中使用 Redux 存储中的值,您可以在此线程中查看解决方案:

https://github.com/react-community/react-navigation/issues/940

解决方案 1:

static navigationOptions = {
  headerTitle: <SomeTitle />
};

SomeTitle 是一个 Redux 连接组件。

解决方案 2:

将状态作为导航助手传递给您的根导航器

<MainNavigator 
  navigation={addNavigationHelpers({ 
    dispatch, 
    state: state.nav, 
    globalState: state 
  })}
/>

并像这样使用它

static navigationOptions = ({ navigation }) => ({
  ... 
  title: globalState.path.to.your.data
});

【讨论】:

  • 感谢您提供许多详细信息的友好回答。但是当我调用一个组件时,我宁愿传递额外的道具。我认为您的方法有效,但我选择了简单的方法。 :P
  • 尽管对你的答案投了赞成票。感谢您的输入。非常感谢
  • 我认为你可以解决这个问题(+200 赏金):*.com/questions/47930049/…