首页 > 解决方案 > 提交表单后如何传递登录失败错误?

问题描述

我有一个用 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>)

标签: reactjsaxios

解决方案


this.state.state.loginError应该是this.state.loginError

而且,axios返回的错误不是简单的消息,而是一个对象。

如果要显示某些内容,则需要访问其中的属性。所以它将是this.state.loginError.response.message或只是将原始状态设置为消息

检查此以供参考:https ://github.com/axios/axios#handling-errors


推荐阅读