4
我正在開發一個android應用程序,從而我的屏幕必須取決於用戶是否登錄。登錄數據存儲在AsyncStorage內部。React Native Redux - 從asyncstorage初始化默認狀態
當應用程序啓動時,它應該從AsyncStorage獲取數據並將其作爲默認狀態。我怎麼能做到這一點?
下面是我的終極版結構
index.android.js
import {
AppRegistry,
} from 'react-native';
import Root from './src/scripts/Root.js';
AppRegistry.registerComponent('reduxReactNavigation',() => Root);
Root.js
import React, { Component } from "react";
import { Text, AsyncStorage } from "react-native";
import { Provider, connect } from "react-redux";
import { addNavigationHelpers } from 'react-navigation';
import getStore from "./store";
import { AppNavigator } from './routers';
const navReducer = (state, action) => {
const newState = AppNavigator.router.getStateForAction(action, state);
return newState || state;
};
const mapStateToProps = (state) => ({
nav: state.nav
});
const user = {};
class App extends Component {
constructor(){
super();
}
render() {
return (
<AppNavigator
navigation={addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.nav
})}
/>
);
}
}
const AppWithNavigationState = connect(mapStateToProps)(App);
const store = getStore(navReducer);
export default function Root() {
return (
<Provider store={store}>
<AppWithNavigationState />
</Provider>
);
}
用戶減速器
import {
REGISTER_USER,
UPDATE_USER,
LOGIN_USER
} from '../../actions/actionTypes';
import { handleActions } from 'redux-actions';
**// here is the default state, i would like to get from asyncstorage**
const defaultState = {
isLoggedIn: false,
user:{},
};
export const user = handleActions({
REGISTER_USER: {
next(state, action){
return { ...state, user: action.payload, isLoggedIn: true }
}
},
LOGIN_USER: {
next(state, action){
return { ...state, user: action.payload, isLoggedIn: true }
}
},
}, defaultState);
您可以給createStore函數初始狀態:http://redux.js.org/docs/api/createStore.html。您可以從異步存儲讀取數據並將其傳遞給createStore()函數,該函數將設置適當的狀態。 –
@AnkitAggarwal你能提供一個例子,我應該從哪裏獲取asyncstorage中的數據並傳入createstore? 這是因爲異步存儲是異步的,我不確定什麼是初始化它的好習慣 –
閱讀關於redux-Persis(https://github.com/rt2zz/redux-persist)並使用這個概念(https:// github.com/rt2zz/redux-persist/blob/master/docs/recipes.md#delay-render-until-rehydration-complete)。不需要使用redux-persist,但您可以從這裏使用補液概念。檢查第二個鏈接延遲渲染 –