2017-01-23 92 views
1

我正在使用React Native和Redux。以下代碼用於創建Redux存儲,並使用AsyncStorage通過檢查authToken的存在來檢查用戶是否已登錄。無法讀取React Native應用啓動時的AsyncStorage值

import {createStore} from 'redux'; 
import {persistStore} from 'redux-persist'; 

async function getAuthToken() { 
    return await AsyncStorage.getItem('authToken'); 
} 

export function createStore(onCompletion:() => void):any { 
    ... 

    const store = createStore(
    reducer, 
    { 
     auth: { 
     authenticated: !!getAuthToken() 
     } 
    }, 
    enhancer); 

    persistStore(store, { 
    storage: AsyncStorage, 
    }, 
    onCompletion); 
} 

商店的創建:

export default class App extends Component { 

    constructor(props) { 
    super(props); 
    this.state = { 
     store: createStore(...), 
    }; 
    } 

    render() { 
    return (
     <Provider store={this.state.store}> 
     <AppNavigator /> 
     </Provider> 
    ); 
    } 
} 

authToken價值得到正確設置,一旦用戶登錄,一旦用戶註銷被刪除。但是應用程序重新啓動後,authToken不會持續。到getAuthToken第一次調用總是返回從AsyncStorage此垃圾值:

{_45:0,_81:0,_65:空,_54:空}

爲什麼會這樣發生?

回答

0

現在您要從AsyncStorage返回一個承諾,您需要返回令牌值。嘗試:

async function getAuthToken() { 
    return await AsyncStorage.getItem('authToken').then((token) => token); 
} 
+0

這不適合我,我仍然會得到相同的結果。我的理解是,「等待」已經是同步的。我也使用相同的「await」模式從AsyncStorage同步獲取authToken,併發送正在工作的HTTP標頭。 – Simian

相關問題