简体   繁体   English

React 中 api 请求的错误处理

[英]Error handling for an api request in React

Im trying to handle errors with api calls.我试图处理 api 调用的错误。 The goal is to show a button only when a successful response from the backend.目标是仅在后端成功响应时显示按钮。 Otherwise do not show the button.否则不显示按钮。 However, even when I get an error, the button will show.但是,即使出现错误,按钮也会显示。 Here is my code:这是我的代码:

handleSubmit = (e) => {
     const {
       firstName, lastName, country, region, address, city, actions
     } = this.props;

     e.preventDefault();

     verify(firstName, lastName, address, city, region, country)
       .then((data) => {
         actions.showSuccessNotification(data);
       }, () => {
         this.setState({
           ...this.state,
           triggerShowButton: true
         });
       });
   }

Here is where I am rendering the button:这是我渲染按钮的地方:

{ (triggerShowButton ) && <Button className={classes.button} onClick= disabled={kycLevelTwoVerified} variant="contained" color="primary">Proceed</Button> }

The function function

verify核实

is a function coming straight from another file.是直接来自另一个文件的 function。 And I imported it.我导入了它。 Here it is:这里是:

async function verifyLevelOne(firstName, lastName, addressLine1, city, region, country) {
  const options = {
    method: 'POST',
    headers: {
      'content-type': 'application/json'
    },
    data: {
      firstName,
      lastName,
      addressLine1,
      city,
      region,
      country
    },
    url: `${BASE}/level1`
  };
  return axios(options);
}

The above code may not be relevant but I just show it here in case.上面的代码可能不相关,但我只是在这里显示以防万一。 Is there any way to make it so that the button is visible only on successful response?有什么方法可以使按钮仅在成功响应时可见?

it's always going to be true because you're telling it它总是真实的,因为你在告诉它

, () => {
         this.setState({
           ...this.state,
           triggerShowButton: true
         });

you should probably put an if statment to check the status of the server or use .catch() incase of an error您可能应该放置一个if语句来检查服务器的状态或使用.catch()出现错误

like so像这样

verify(firstName, lastName, address, city, region, country)
       .then((data) => {
         actions.showSuccessNotification(data);
       },() => {
         this.setState({
           ...this.state,
           triggerShowButton: true
         }).catch((error) => {
           //handle error
           console.log(error)
         })

or alternate solution或替代解决方案

verify(firstName, lastName, address, city, region, country)
       .then((data) => {
         actions.showSuccessNotification(data);
       },() => {
         if(dataIsVerified){ // dataIsVerified = you need to check if the data is ok it's up to you i just made it up
         this.setState({
           ...this.state,
           triggerShowButton: true
         })
    } else {throw "error"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM