[英]why <Redirect to='/vacations' /> Does not work
我正在尝试使用主页上的登录表单制作简单的应用程序,然后重定向到假期页面。 我在尝试将/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='/' />
}
})
}
}
您不能在render
之外返回Redirect
。 如果你想在一些命令式代码之后重定向,你应该使用history.push()
apiCheck = () =>{
fetchResource().then(res => this.props.history.push('/path'))
}
history
对象,它在用react-router-dom
withRouter
HOC 包装任何组件(已经在Router
下)时withRouter
export default withRouter(MyComponent)
我认为您实际上并不是在渲染组件。 您必须在渲染方法中调用userLogin()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.