screenProps.object returns navigationOptions 中始终为 null

screenProps.object returns ALWAYS null in navigationOptions

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

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

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

我在 componentWillMount()

上使用 Redux 获取了 outfitDetail 道具
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});

但是在Profile界面,也无法得到screenProps.username

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

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

解决方案一:

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

其中 SomeTitle 是 Redux 连接组件。

方案二:

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

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

然后像这样使用它

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