【发布时间】:2020-07-21 14:57:01
【问题描述】:
我在反应组件中有一个表单。
当我点击提交按钮时,我调用了signin()。在 signin() 中,出现错误,因为我可以在 chrome 控制台中看到输出,但它闪烁得如此之快,我无法阅读它。然后页面刷新,错误消息从控制台消失了。
为什么我的表单会重新呈现页面?以及如何抑制重新渲染以便读取错误?
这是我的组件:
import React, { Component } from 'react';
import './login.scss';
import axios from '../axios/axiosInstance';
class Login extends Component {
constructor() {
super();
this.usernameRef = React.createRef();
this.passwordRef = React.createRef();
}
signin() {
axios.get('/auth', {headers: {
username: this.usernameRef.current.value,
password: this.passwordRef.current.value}}).then(response => {
console.log('response=', response);
}).catch(err => {
console.log('err=', err);
});
}
render() {
return (
<div className="login-container">
<form onSubmit={this.signin}>
<div className="flex-row-end">
<div className="form-element flex-column-end">
<input type="text"
placeholder="Username or email"
name="username"
ref={this.usernameRef}
required />
</div>
<div className="form-element flex-column-end">
<input type="password"
placeholder="Password"
name="password"
ref={this.passwordRef}
required />
</div>
<div className="login-submit">
<button className="submit-login-button" type="submit"><i className="fas fa-sign-in-alt"> </i>Sign In</button>
</div>
</div>
</form>
</div>
);
}
};
export default Login;
如您所见,在 signin() 中,我使用 axios 向我的后端发送带有用户凭据的请求。在后端,日志显示没有收到请求的记录。因此,错误必须在请求发送之前发生。但是我需要一种方法来抑制页面的重新呈现,以便我可以看到错误消息是什么。
非常感谢。
【问题讨论】:
标签: reactjs forms submit rerender