有人可以帮我吗?当通过axios进行的结果正确时,我无法将“重定向”的状态更改为“真”。因此,我们永远不会进入在返回中进行重定向的循环。我真的认为问题出在“ .then(功能(响应){...}”)部分。此外,如果我将booleen的“重定向”直接初始化为“ true”,则重定向有效,因此问题不在重定向中]
import React from 'react';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router';
import {
MDBContainer, MDBRow, MDBCard, MDBCardBody, MDBModalFooter,
} from 'mdbreact';
import './connexion.css';
import axios from 'axios';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
password: null,
email: null,
redirection: false, //initialize the redirection status as false
error: '',
};
}
change = async e => {
await this.setState({
[e.target.id]: e.target.value,
});
}
handleSubmit = e => {
const { email, password } = this.state;
if (password && email) {
console.log(this.state);
let formData = new FormData();
formData.append("email",this.state.email);
formData.append("password",this.state.password);
const url = "http://localhost:8888/login/login.php";
axios.post(url, formData)
.then(function(response) {
this.setState({redirection: true}); //if the login works, it changes the redirection status to true, redirection is in the render
console.log("successful login", response);
})
.catch((error) => {
if(error.response === 403){
console.log("email or password wrong", error);
}
});
} else {
this.setState({
error: 'File in all cases !',
});
}
setTimeout(() => {
this.setState({
error: '',
});
}, 2000);
e.preventDefault();
}
render() {
const { error } = this.state;
const {redirection } = this.state;
if(redirection){
//redirection to the home page
return <Redirect to="/homePage"/>;
}
return (
<div>
<h1 className="myBibli">MyBibli</h1>
<MDBContainer className="containerConnexion">
<MDBRow>
<MDBCard>
<MDBCardBody className="mx-4">
<form onSubmit={this.handleSubmit}>
<div className="text-center">
<h2 className="dark-grey-text mb-5">
Connexion
</h2>
</div>
<label htmlFor="email" className="grey-text">
Adresse mail
<input
type="email"
id="email"
name="email"
className="form-control"
onChange={this.change}
/>
</label>
<br />
<label htmlFor="password" className="grey-text">
Mot de passe
<input
type="password"
id="password"
name="password"
className="form-control"
onChange={this.change}
/>
</label>
<p className="font-small blue-text d-flex justify-content-end pb-3">
</p>
<div className="text-center mb-3">
<button type="submit" className="btn btn-primary" onClick={this.handleSubmit}>Se Connecter</button>
{
error && (
<p className="error">{error}</p>
)
}
</div>
<p className="font-small dark-grey-text text-right d-flex justify-content-center mb-3 pt-2" />
</form>
</MDBCardBody>
<MDBModalFooter className="mx-5 pt-3 mb-1">
<p className="font-small grey-text d-flex justify-content-end">
<Link to="/inscription" className="blue-text ml-1">
SignUp
</Link>
</p>
</MDBModalFooter>
</MDBCard>
</MDBRow>
</MDBContainer>
</div>
);
}
}
export default Login;
有人可以帮我吗?当通过axios进行的结果正确时,我无法将“重定向”的状态更改为“真”。因此,我们永远不会进入在返回中进行重定向的循环。我...
您的.then
应绑定到this
: