我试图让用户登录到我的应用程序中。我尝试了几种技术,但我不知道如何在应用程序启动时将数据读入状态。
现在我有以下几点:
const getInitialState = () => {
var _initState = {
auth: new AuthInitialState(),
global: (new GlobalInitialState())
};
return _initState;
};
export default function configureStore() {
const store = createStoreWithMiddleware(reducer, load(APP_STORAGE) || getInitialState());
store.subscribe(() => {
if(!load('debug')) {
save(APP_STORAGE, store.getState());
}
});
return store;
};
const createStoreWithMiddleware = applyMiddleware(
thunk,
localStorageMiddleware,
logger
)(createStore)其中,加载和保存方法负责将数据保存到AsyncStorage (使用react本机-简单存储)。
export const load = (key) => {
return store.get(key);
}
export const save = async (key, data) => {
store.save(key, JSON.stringify(data));
}我的根的呈现是当前的:
render() {
const store = configureStore();
return (
<Provider store={store}>
<MyApp/>
</Provider>
);
}数据正在被正确保存(通过保存订阅服务器),但是在热重新加载或应用程序重新启动时没有正确地重新加载数据。因此,我的用户每次都会被注销。
最后,我还想应用这一技术,在应用程序启动时导航到正确的页面。
对我如何处理这件事有什么建议吗?
发布于 2016-09-19 20:58:42
您可以使用保留-持久化来实现这一点:
import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import { AsyncStorage } from 'react-native';
export default function configureStore() {
const store = createStore(reducers, getInitialState(), compose(
applyMiddleware([
thunk,
localStorageMiddleware,
logger
]),
autoRehydrate()
)
);
persistStore(store, { storage: AsyncStorage });
return store;
};这样,每次加载应用程序时,存储都会从本地存储中得到补充。您不必处理AsyncStorage,一切都是自动为您完成的。您可以根据您的需要定制读文档 of redux-persist (添加whitelist、blacklist、商店再水化时的回调)。
发布于 2016-09-19 20:30:21
你的基本方法在我看来不错。
然而,反应-本地-简单-商店紧张的状态为您。当您在保存函数中运行JSON.stringify()时,在应用程序的下一次启动期间加载它时,它将无法正确地解码。
有关更多详细信息,请参阅反应-本地-简单-商店的代码基。
要解决这一问题,从保存函数中删除。
export const save = async (key, data) => {
store.save(key, data);
}https://stackoverflow.com/questions/39581115
复制相似问题