簡體   English   中英

React 中 api 請求的錯誤處理

[英]Error handling for an api request in React

我試圖處理 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> }

function

核實

是直接來自另一個文件的 function。 我導入了它。 這里是:

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

上面的代碼可能不相關,但我只是在這里顯示以防萬一。 有什么方法可以使按鈕僅在成功響應時可見?

它總是真實的,因為你在告訴它

, () => {
         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"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM