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.
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.
You just need to export the store from the module where it created with createStore() . Also, it shouldn't pollute the global window object.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With