繁体   English   中英

使用React Navigation访问Redux状态

[英]Access Redux state using React Navigation

我使用以下导航器使用React-Navigation

const Navigator = StackNavigator(
  {
    Home: {
      screen: Home
    },
    User: {
      screen: User
    }
  }
)

我的User组件:

export default class User extends Component {
  static navigationOptions = {
    title: () => 'User'
  }

  render() {
    return (
      <Text>This is the user page.</Text>
    )
  }
}

我希望User场景导航栏的标题是用户的名字。 该名称保持在Redux状态。

由于我从Home场景访问User场景,我可以在推送场景时传递用户的名字:

this.props.navigation.navigate('User', {name: user.name})

但是,如果用户的名称在更新时, User ,然后导航标题不会被更新。 我能看到的唯一解决方案是从navigationOptions访问Redux状态。 有没有办法做到这一点或更好的方法来处理这个问题? 谢谢。

我从一个关于react-navigations GitHub repo的问题中找到了2个解决方案。

1)每次道具改变时更新this.props.navigation.state:

componentWillReceiveProps(nextProps) {
  if (nextProps.totalCharge) {
    this.props.navigation.setParams({ totalCharge });
  }
}

2)创建连接到Redux状态的NavigationTitle组件:

static navigationOptions = {
  title: (navigation) => <MyConnectedTitle navigation={navigation} />
}

我假设你在打电话

this.props.navigation.navigate('User', {name: user.name})

来自一个组件。 因此,您应该使用用户名在组件中mapStateToProps ,然后将其作为{name: ...变量传递。

例如:

export class Component {
  render() {
    return (
      <View>
        <Button onPress={() => this.props.navigation.navigate('User', {name: this.props.userName})}
      </View>
    )
  }
}

const mapStateToProps = (state) => ({
  userName: state.user.name
})

export default connect(mapStateToProps)(Component)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM