I am trying to make simple app with login form on the home page, which redirects then to vacations page. I faced a problem when trying to make /vacations
page private. Here is the code:
import React, { Component } from 'react';
import { Redirect } from "react-router";
import axios from "axios"
class Nav extends Component {
constructor() {
super();
this.state = {
userName: '',
password: '',
}
this.userLogin = this.userLogin.bind(this);
}
userLogin() {
let userToChack = {
userName: this.state.userName,
password: this.state.password,
}
axios.post(`http://localhost:3000/api/login`, userToChack)
.then(res => {
if (res.data !== "") {
// if user name and password OK
document.getElementById(`helloUser`).innerText = `Hello ${this.state.userName}`;
document.getElementById(`login`).innerText = `Logout`;
return <Redirect to='/vacations' />
} else {
// if user name or password NOT OK
console.log("user can't login");
document.getElementById(`helloUser`).innerText = ``;
document.getElementById(`login`).innerText =`Login`;
return <Redirect to='/' />
}
})
}
}
You can't return Redirect
outside render
. If you want to redirect after some imperative code you should use history.push()
apiCheck = () =>{
fetchResource().then(res => this.props.history.push('/path'))
}
history
object it's available when wrapping any component (that already is under Router
) with withRouter
HOC from react-router-dom
export default withRouter(MyComponent)
I don't think that you're actually rendering the component. You have to call userLogin()
in your render method.
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.