I am working on a validation form which fetches data from API. So, I have a state called "isLogged".
I initialiazed it as false then if the auth works, it changes to true.
So, I am trying to render an if-else statement with the if condition being the "isLogged" === true
then I should navigate the user to Dashboard page
else when the "isLogged" is false, i render the whole form component,
but i dont have any idea how can i navigate the user between screens without onPress or rendering a component, i just would like to call a function to navigate or something else
CODE:
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: null,
password: null,
isLogged: false,
}
}
render() {
if (this.state.isLogged) {
# the command which navigate the user to Dashboard page
} else {
return (
# The whole component code>
);
}
}
}
you can use this:
render() {
if (this.state.isLogged) {
this.props.navigation.navigate("Dashboard");
}
return (
# The whole component code>
);
}
A better way to check these type of things is using Lifecycle hooks provided by react, because you make a clean render method as much as possible. It's componentDidMount.
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: null,
password: null,
isLogged: false,
}
}
componentDidMount(){
if (this.state.isLogged) {
this.props.navigation.navigate("Dashboard");
}
}
render() {
return (
# The whole component code>
);
}
}
In Case you find error like, can find navigation of undefined, You will need to pass it via highercomponent " WithNavigation
". It will add navigation object to your props. Following is the code to use WithNavigation
.
import { withNavigation } from 'react-navigation';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: null,
password: null,
isLogged: false,
}
}
componentDidMount(){
if (this.state.isLogged) {
this.props.navigation.navigate("Dashboard");
}
}
render() {
return (
# The whole component code>
);
}
}
export default withNavigation(Login);
For more on lifecycle hooks, read this article
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.