我正在尝试使用主页上的登录表单制作简单的应用程序,然后将其重定向到假期页面。尝试将/vacations
页设为私有时遇到问题。这是代码:
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='/' />
}
})
}
}
答案 0 :(得分:1)
您不能在Redirect
以外返回render
。如果要在执行某些命令性代码后重定向,则应使用history.push()
apiCheck = () =>{
fetchResource().then(res => this.props.history.push('/path'))
}
history
对象,当使用Router
中的withRouter
HOC包装任何组件(已经在react-router-dom
下)时可用。
export default withRouter(MyComponent)
答案 1 :(得分:0)
我认为您实际上并不是在渲染组件。您必须在渲染方法中调用userLogin()
。