美文网首页
RN-React-Redux 数据持久化存储redux-pers

RN-React-Redux 数据持久化存储redux-pers

作者: 精神病患者link常 | 来源:发表于2022-05-26 22:13 被阅读0次

创建reduces

import { configureStore,combineReducers } from '@reduxjs/toolkit';

import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import AsyncStorage from '@react-native-async-storage/async-storage'

import themeReducer from './theme';

const persistConfig = {
  key: 'root',
  storage:AsyncStorage, //指定存储位置,一定要写
  blacklist: []
}

let allReducers = combineReducers({
  theme:themeReducer
})
const persistedReducer = persistReducer(persistConfig, allReducers)
let store = configureStore({
  reducer:persistedReducer,
  middleware: (getDefaultMiddleware) => //不写报错
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
})
let persistore = persistStore(store)

// 获取持久化存储信息
AsyncStorage.getItem('persist:root').then((data:any)=>{
  console.log('获取持久化存储信息=',data);
})

export {persistore}
export default store
import { StatusBar } from 'expo-status-bar';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import useCachedResources from './src/hooks/useCachedResources';
import Navigation from './src/navigation';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react'

import store,{persistore} from './src/redux/store'

export default function App() {
  const isLoadingComplete = useCachedResources();

  if (!isLoadingComplete) {
    return null;
  } else {
    return (
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistore}>
          <SafeAreaProvider>
            <Navigation/>
            <StatusBar />
          </SafeAreaProvider>
        </PersistGate>
      </Provider>
    );
  }
}

即可,存到redux中的值,关闭app重新运行,值依然存在

#

触发下changeTheme方法,然后关闭app重新运行,在页面中打印

image.png image.png

https://redux-toolkit.js.org/usage/usage-guide#use-with-redux-persist

相关文章

网友评论

      本文标题:RN-React-Redux 数据持久化存储redux-pers

      本文链接:https://www.haomeiwen.com/subject/zsppprtx.html