如何显示React内部的API错误句柄?

时间:2019-08-02 08:26:16

标签: reactjs firebase api error-handling postman

在登录时,如果电子邮件和密码为空,则会引发如下错误:

{
    "errors": {
        "email": "please enter valid emails",
        "password": "please enter password"
    }
}

在我发送的API /登录名上:

 {
    "email":"",
    "password":""
}

我想在我的React.js前端显示此错误,所以我尝试以下代码:

import React, { Component } from 'react'
import { withStyles } from '@material-ui/styles';
import PropTypes from 'prop-types'
import AppIcon from '../images/icon.png'
//mivi stuff
import Grid from '@material-ui/core/Grid';
import  Typography  from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import axios from 'axios';




class login extends Component {
    constructor(){
        super();
        this.state ={
            email:'',
            password:'',
            loading:false,
            error: {}

        }
    }
    handleChnage = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        })
    }
    handleSubmit = (event) => {
       // console.log('hi');
        event.preventDefault();
        this.setState({
            loading:true
        });
        const userData ={
            email:this.state.email,
            password:this.state.password
        }
        axios.post('/login', userData)
        .then((res) =>{
            //console.log(res.data)
            this.setState({
                loading:false
            });
            this.props.history.push('/');
        })
        .catch((err) =>{
            this.setState({
                errors:err.response.data,   
                loading:false
            })
        })
    }
    render() {
        const {classes} = this.props;
        const {error ,loading} = this.state
        return (
           <Grid container className={classes.form}>
                <Grid item sm />
                <Grid item sm >
                   <img src={AppIcon} alt="app cion" className={classes.image}/> 
                   <Typography variant="h2" className={classes.pagetitle}>Login</Typography>  
                   <form noValidate onSubmit={this.handleSubmit}>
                        <TextField id="email" name="email" type="email" label="Email" className={classes.textfeild}
                         helperText={error.email} error={error.email ? true : false}  value={this.state.email} onChange={this.handleChnage} fullWidth />
                        <TextField id="password" name="password" type="password" label="Password" className={classes.textfeild}
                            helperText={error.password} error={error.password ? true : false}    value={this.state.password} onChange={this.handleChnage} fullWidth />
                        <Button type="submit" variant="contained" color="primary" className={classes.button}>Login </Button>
                   </form>
                 </Grid>
                <Grid item sm />
           </Grid>
        )
    }
}

login.propTypes ={
classes:PropTypes.object.isRequired
}

export default withStyles(styles)(login);

当用户名和密码为空并且单击时,这些错误不会显示。我该如何解决?

因为API错误位于错误对象的内部,所以我希望这是为什么它不显示,但是我无法将其改回来,我想显示电子邮件或密码是否为空。我想在这里显示该错误:

helperText={error.email} helperText={error.password}一侧

2 个答案:

答案 0 :(得分:2)

将您的.catch块更新为

.catch((err) =>{
       const { errors } = err.response.data;
        this.setState({
            errors,   
            loading:false
        })
    })

答案 1 :(得分:1)

您的状态为error,而您试图将值分配给errors,则需要将状态设置为error。因为您使用error.emailerror.password来显示错误。

.catch((err) =>{
     this.setState({
         error:err.response.data,   
         loading:false
     })
})

更新

由于err.response.data的原因,

  

错误:对象{电子邮件:“请输入有效的电子邮件”,密码:“请输入密码”}

您需要像这样从errors访问err.response.data

.catch((err) =>{
     this.setState({
         error:err.response.data.errors,   
         loading:false
     })
})