2017-10-17 75 views
1

我有以下異步功能用於通過REST服務驗證有效的用戶憑證;異步功能中的反應設置狀態

async doesLoginExist(regCode) { 
    if (loginCode.match(loginCodePattern)) { 
     try { 
     await LoginService.getUserByLoginCode(); 
     return {}; 
     } catch (err) { 
     if (err.status === 404) { 
      return { 
      error: 'Your login code is not recognized.', success: null 
      }; 
     } 
     return { 
      error: 'Service is temporarily unavailable.', success: null 
     }; 
     } 
    } 
    return {}; 
    } 

但是,當我嘗試在此函數中設置某些狀態時;

async doesLoginExist(regCode) { 
    await this.setState({ canProceed: false }); 
    if (loginCode.match(loginCodePattern)) { 
     try { 
     await LoginService.getUserByLoginCode(); 
     await this.setState({ canProceed: true }); 
     return {}; 
     } catch (err) { 
     if (err.status === 404) { 
      return { 
      error: 'Your login code is not recognized.', success: null 
      }; 
     } 
     return { 
      error: 'Service is temporarily unavailable.', success: null 
     }; 
     } 
    } 
    return {}; 
    } 

似乎不再對我{錯誤,成功}對象正確地返回給調用者,這最終被用作屏幕上顯示的驗證消息。另一個小問題是在輸入登錄代碼的文本框上輸入autoFocus也不起作用。

有沒有其他方法我應該在這個函數內設置狀態?

+0

你爲什麼在this.setState上使用await? – linasmnew

+0

嗯,我想這不是必須的。但是,當我把它拿出來的同樣的問題。 – deanmau5

+1

您還沒有足夠清楚地描述問題,「不再似乎正確地返回我的{錯誤,成功}是什麼意思? – linasmnew

回答

0
  1. 確保doesLoginExist正確地綁定到組件的上下文。由於缺乏信息肯定不能確定,但​​這是非常普遍的問題。 Read more here 示例如何綁定doesLoginExist本身 - 你必須明確地做一個構造函數

    constructor() { 
        super(); 
        this.doesLoginExist = this.doesLoginExist.bind(this); 
    } 
    
    async doesLoginExist() { 
        this.setState({ canProceed: false }); 
        ... 
    } 
    
  2. 可選重構由doesLoginExist提取this.setState電話 - 成另一種方法,它會增加doesLoginExist

    重用性
    handleSomethingHappened =() => { 
        this.setState({ canProceed: false }); 
        const result = await doesLoginExist(regCode) 
        this.setState({ canProceed: true }); 
    } 
    

乾杯。