要在成功登录后访问主页,用户需要刷新整个页面(否则他将不会自动重定向到主页)。可能的问题是什么,如何解决?这是我的源代码:
App.js
class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route path='/' exact component={ MainPage }></Route>
<Route path='/login' component={ LogIn }></Route>
<Route component={ NotFoundPage }></Route>
</Switch>
</BrowserRouter>
);
}
}
export default App;
LogIn.js
const userIdRegex = RegExp(
/^[uU]*1+[0-9]*$/
);
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
userId: null,
password: null,
fullName: undefined,
responseError: false,
loggedIn: false,
formErrors: {
userId: "",
password: ""
}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange = e => {
e.preventDefault();
const { name, value } = e.target;
let formErrors = { ...this.state.formErrors };
switch (name){
case "userId":
formErrors.userId = userIdRegex.test(value)
? ""
: "Invalid user ID";
break;
case "password":
formErrors.password =
value.length < 8 ? "Invalid password" : "";
break;
default:
break;
}
this.setState({ formErrors, [name]: value }, () => console.log(this.state));
};
handleSubmit = e => {
e.preventDefault();
axios.post('url', { userId: e.target.elements.userId.value,
password: e.target.elements.password.value })
.then((response) => {
if(response.status=200){
this.setState({ loggedIn: true });
let responseJSON = response;
sessionStorage.setItem("userData", responseJSON);
} else {
console.log("Log In Error");
}
}).catch((error) => {
console.log(error);
this.setState({ responseError: true });
});
};
render() {
if ( this.state.loggedIn ) {
return (<Redirect to={'/'} />);
}
if ( sessionStorage.getItem('userData') ){
return (<Redirect to={'/'} />);
}
const { formErrors } = this.state;
const responseError = this.state.responseError;
// const loggedIn = this.state.loggedIn;
// const { from } = this.props.location.state || '/';
return (
<div className="wrapper">
<div className="form-wrapper">
<img src={Logo} className="App-logo" alt="Logo" />
<p>To Log In enter your user ID and password.</p>
<form onSubmit={this.handleSubmit} noValidate>
<div className="userId">
<input
autoFocus
className={formErrors.userId.length > 0 ? "error" : null}
placeholder="User ID"
type="text"
name="userId"
noValidate
defaultValue="u"
onChange={this.handleChange}
/>
{formErrors.userId.length > 0 && (
<span className="errorMessage">{formErrors.userId}</span>
)}
</div>
<div className="password">
<input
className={formErrors.password.length > 0 ? "error" : null}
placeholder="Password"
type="password"
name="password"
noValidate
onChange={this.handleChange}
/>
{formErrors.password.length > 0 && (
<span className="errorMessage">{formErrors.password}</span>
)}
</div>
<div className="createAccount">
<button type="submit" disabled={!this.state.userId} disabled={!this.state.password}>
Log in
</button>
</div>
</form>
{ responseError==true && (
<span className="response-error errorMessage">Please enter valid user values</span>
) }
</div>
</div>
)}
}
export default LogIn;
MainPage.js
class MainPage extends Component {
constructor(props) {
super(props);
this.state = {
redirect: false,
}
this.logout = this.logout.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
}
componentDidMount() {
if( sessionStorage.getItem('userData') ){
console.log('User Logged In');
} else {
this.setState({redirect: true})
}
}
logout(){
sessionStorage.setItem('userData', '');
sessionStorage.clear();
this.setState({redirect: true})
}
render(){
if (this.state.redirect) {
return (<Redirect to={'/login'} />);
}
return(
<div>
<p>Welcome</p>
<button onClick={this.logout}>Logout</button>
</div>
);
}
}
export default MainPage;
当我从MainPage.js中删除componentDidMount()方法时,它解决了重定向问题,但是无需通过URL登录即可访问主页。
答案 0 :(得分:2)
所有路线组件都可以访问道具中的history
对象,因此您可以在成功登录this.props.history.push('/')
组件后执行LogIn
。
class LogIn extends Component {
// ...
handleSubmit = e => {
e.preventDefault();
axios
.post("url", {
userId: e.target.elements.userId.value,
password: e.target.elements.password.value
})
.then(response => {
if (response.status === 200) {
this.setState({ loggedIn: true });
sessionStorage.setItem("userData", response);
this.props.history.push("/");
} else {
console.log("Log In Error");
}
})
.catch(error => {
console.log(error);
this.setState({ responseError: true });
});
};
// ...
}