如何让用户在 react-native 中保持登录状态(又名,状态持久性)

How to keep user logged in (Aka, state persistency) in react-native

我试图让用户在我的应用程序中保持登录状态。我尝试了几种技术,但我不知道如何在应用程序启动时将数据读回状态。

现在我有以下内容:

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)

其中load和save方法负责将数据保存到AsyncStorage(使用react-native-simple-store)

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>
    );
}

数据已正确保存(通过保存订阅者),但在热重载或应用重新启动时未正确重新加载。因此我的用户每次都被注销。

最后我也想应用这个技术在应用程序启动时导航到正确的页面。

关于我如何处理这个问题有什么建议吗?

我觉得你的基本方法不错。

但是,react-native-simple-store 会为您将状态字符串化。正如您 运行 JSON.stringify() 在您的保存功能中一样,在下次启动您的应用程序时加载它时将无法正确解码。

有关详细信息,请参阅 react-native-simple-store's codebase


要解决此问题,从您的保存功能中删除 JSON.stringify()

export const save = async (key, data) => {
    store.save(key, data);
}

您可以使用 redux-persist 来实现:

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,一切都会自动为您完成。您可以 read the docsredux-persist 来根据您的需要自定义它(添加一个 whitelist、一个 blacklist、商店补水时的回调..)