reactjs - 提交表单后如何传递登录失败错误?
问题描述
我有一个用 reactJS 编写的登录组件,它使用 axios 来执行登录端点。如果由于正当原因登录失败,我将 loginerror 保存在 state 中。然后我在 JSX 的返回部分有一个 div 标签,它应该显示错误。但是,不会显示此消息。我知道 JSX 在异步调用完成之前运行。我该如何解决这个问题?
handleSubmit(event) {
const { email, password} = this.state;
axios
.post(
"http://localhost:4000/users/login",
{
email: email,
password: password
}
)
.then(response => {
if (response.status ===200) {
this.props.handleSuccessfulAuth(response.data);
}
})
.catch(error => {
this.setState({loginErrors:error})
});
event.preventDefault();
}
return(<div>{this.state.state.loginError}</div>)
解决方案
this.state.state.loginError
应该是this.state.loginError
而且,axios返回的错误不是简单的消息,而是一个对象。
如果要显示某些内容,则需要访问其中的属性。所以它将是this.state.loginError.response.message
或只是将原始状态设置为消息
推荐阅读
- ajax - 使用带有 CORS 策略的 ajax 调用问题调用 IIS 发布的 Web api
- angular - 如何使用量角器打字稿在地图元素上单击选择拖动
- angular - 在 Angular 7 中使用 Ivy 编译器是否正确?
- google-analytics - GTM - 历史更改触发器不跟踪初始页面加载
- java - 使用休眠的 EntityNotFoundException 句柄
- node.js - 安装node-sass文件后出错
- ssl - 如何生成 SSL 证书和公钥进行加密?
- javascript - 我网站上的 Instagram 提要 javascript 不起作用
- c# - 在 C# 中的类之间共享对象
- installation - NSIS GetParent 函数抛出未知错误