Currently, I am creating connection and registration screens, with a profile button on the bottom tab bar. The objective is for the user to be directed to their profile page if they are logged in (user data stored in Redux), or to a landing screen with login and subscribe buttons if not.
I'm wondering how to automatically navigate to the landing page whenever the "Profile" button on the bottom tab bar is clicked and the Redux store is empty.
Below is the code snippet for the profile:
// Screens / Profil.js
import React from "react";
import { StyleSheet, View, Text, Button } from "react-native";
import { color } from "../constants/color";
import { connect } from "react-redux";
class Profil extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
if (this.props.currentUser === null) {
this.props.navigation.navigate("Landing");
}
}
render() {
const { currentUser } = this.props;
console.log(currentUser);
if (currentUser === null) {
return (
<View style={styles.mainContainer}>
<Text>You are not connected</Text>
</View>
);
} else {
return (
<View style={styles.mainContainer}>
<Text>Welcome {currentUser.user.username}</Text>
<Button title="Log out" onPress={this._disconnection} />
</View>
);
}
return null;
}
}
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
backgroundColor: color.whisper
}
});
const mapStateToProps = state => {
return {
currentUser: state.connection.currentUser
};
};
export default connect(mapStateToProps)(Profil);
Initially, when I click on Profile, it correctly redirects me to the landing page:
https://i.sstatic.net/fLeEn.jpg
However, upon clicking on Profile again, it does not redirect me back to the landing page:
https://i.sstatic.net/hFMdt.jpg
I suspect this issue arises due to the component not re-rendering itself. How can I ensure constant redirection based on the Redux state variable?
UPDATE: My stack Navigator
const ProfilStackNavigator = createStackNavigator({
Profil: {
screen: Profil,
navigationOptions: {
title: "Profil"
}
},
Landing: {
screen: Landing,
headerMode: "none",
navigationOptions: {
header: null
}
},
SignUp: {
screen: SignUp,
navigationOptions: {
title: "Inscription"
}
},
SignIn: {
screen: SignIn,
navigationOptions: {
title: "Connection"
}
}
});