简体   繁体   中英

Access Redux state using React Navigation

I have the following Navigator using React-Navigation :

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

And my User component:

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

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

I want the title of the User scene's navigation bar to be the user's name. The name is kept within the Redux state.

Since I'm accessing the User scene from the Home scene, I could pass the user's name when I push the scene:

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

However if the user's name is updated when on the User , then the navigation title will not be updated. The only solution I can see is to access the Redux state from within navigationOptions . Is there a way to do this or a better way to handle this issue? Thanks.

I found 2 solutions to my answer from an issue on react-navigations GitHub repo.

1) Update this.props.navigation.state every time the props change:

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

2) Create a NavigationTitle component that is connected to the Redux state:

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

I'm assuming that you are calling

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

from a component. Therefore you should mapStateToProps in the component with the user's name and then pass it as the {name: ... variable.

For instance:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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