如何将localStorage迁移到AsyncStorage

时间:2018-12-07 06:10:48

标签: javascript reactjs react-native redux

我已经有用于我的Web项目的localStorage代码。

我的localStorage文件,用于保存和加载localStorage。

// localStorage.js
export const loadState = () => {
  try {
    localStorage.clear();
    const version = localStorage.getItem("version");
    // you can update the version to init the persist state
    if (version !== "0.1") {
      localStorage.clear();
      localStorage.setItem("version", "0.1");
    }
    const serializedState = localStorage.getItem("state");
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;
  }
};
export const saveState = state => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem("state", serializedState);
  } catch (err) {
    // Ignore write errors.
  }
};

还有我的存储文件来初始化redux存储。

// store.js
import persistReducer from "./reducers/persistReducer";
...

import { loadState, saveState } from "./localStorage";

const persistedState = loadState();

const store = createStore(
  combineReducers({
    persist: persistReducer,
    ...
  }),
  persistedState,
  composeWithDevTools(applyMiddleware(thunk))
);

store.subscribe(
  throttle(() => {
    saveState({
      persist: store.getState().persist
    });
  }, 1000)
);

ReactDOM.render(
  <Provider store={store}>
    ...
  </Provider>,
  document.getElementById("root")
);
registerServiceWorker();

现在我想将此代码迁移到AsyncStorage,如何简单地更改此代码以适应我的本机应用程序项目?

0 个答案:

没有答案