Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 973
Pav Sidhu Avatar asked Feb 20 '17 00:02

Pav Sidhu


People also ask

How do I get my state from Redux?

You may call getState() inside this callback to read the current state tree. It is reasonable to expect that the store's reducer is a pure function, so you may compare references to some deep path in the state tree to learn whether its value has changed.

How do I access Redux state outside component?

You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.


2 Answers

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} />
}
like image 163
Pav Sidhu Avatar answered Sep 23 '22 11:09

Pav Sidhu


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)
like image 22
wmcbain Avatar answered Sep 24 '22 11:09

wmcbain