2017-07-03 58 views
0

我正在嘗試檢查用戶是否已通過身份驗證。我通過檢查asyncStorage一些唱片做到這一點,我有以下的代碼解決componenDidMount中的AsyncStorage諾言

App.js

let AuthService = require('./app/layouts/AuthService/AuthService.js'); 
export default class App extends React.Component { 

    componentDidMount() { 
     AuthService.getAuthInfo((err, authInfo) => { 
      this.setState({ 
       checkingAuth: false, 
       isLoggedIn: authInfo != null 
      }) 
     }); 
    } 
} 

Auth.js

'use strict'; 

let AsyncStorage = require('react-native').AsyncStorage; 
let _ = require('lodash'); 

const authKey = 'auth'; 
const userKey = 'user'; 

class AuthService { 
    getAuthInfo(cb){ 
     AsyncStorage.multiGet([authKey, userKey], (err, val)=> { 
      if(err){ 
       return cb(err); 
      } 
      if(!val){ 
       return cb(); 
      } 
      let zippedObj = _.zipObject(val); 
      if(!zippedObj[authKey]){ 
       return cb(); 
      } 
      let authInfo = { 
       header: { 
        Authorization: 'Basic ' + zippedObj[authKey] 
       }, 
       user: JSON.parse(zippedObj[userKey]) 
      } 
      return cb(null, authInfo); 
     }); 
    } 
} 
module.exports = new AuthService(); 

在app.js,我試圖用這個函數來自Auth.js,但我沒有得到函數的迴應,我在進入AsyncStorage函數之前從getAuthInfo獲取控制檯日誌。我很新的反應原生和ES6,我認爲是承諾或異步問題,但我不能讓它的工作。在app.js中,我重寫了一個ActivityIndi​​cator,所以我不會用checkingAuth和isLoggedIn阻止UI。 我試圖在app.js中使用一些.then,但沒有任何結果。

回答

0

首先,你返回你的回調函數而不是調用它。嘗試刪除return這樣的電話:cb(null, authInfo);

+0

謝謝!那工作 –