解决componenDidMount中的AsyncStorage承诺

时间:2017-07-03 17:44:56

标签: javascript react-native ecmascript-6 jsx

我试图检查用户是否经过身份验证。我通过检查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而没有结果。

1 个答案:

答案 0 :(得分:0)

首先,您返回回调函数而不是调用它。尝试通过删除return来调用它:cb(null, authInfo);