【问题标题】:Error handling for an api request in ReactReact 中 api 请求的错误处理
【发布时间】:2021-12-29 10:27:30
【问题描述】:

我正在尝试通过 api 调用处理错误。目标是仅在后端成功响应时才显示按钮。否则不显示按钮。但是,即使出现错误,按钮也会显示。这是我的代码:

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
         });
       });
   }

这里是我渲染按钮的地方:

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

功能

验证

是直接来自另一个文件的函数。我导入了它。这里是:

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);
}

上面的代码可能不相关,但我只是在此处显示以防万一。有什么方法可以使按钮仅在成功响应时可见?

【问题讨论】:

    标签: javascript reactjs promise axios conditional-statements


    【解决方案1】:

    它总是正确的,因为你在告诉它

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

    您可能应该使用if 声明来检查服务器的状态或使用.catch() 以防出现错误

    像这样

    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)
             })
    

    或替代解决方案

    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"}
    
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      相关资源
      最近更新 更多