如何在 reactjs 中持久化或保存状态?

时间:2021-03-10 05:41:38

标签: javascript reactjs ecmascript-6 react-state state-saving

我目前正在使用 ReactJS 开发单页应用程序。 我必须使用本地存储来保存状态,但这并不安全。 我想知道是否有任何可能的安全方式将本地存储用于状态?

1 个答案:

答案 0 :(得分:1)

您可以使用 redux-persist 包来保持状态。

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import rootReducer from '../_reducers';
import { composeWithDevTools  } from 'redux-devtools-extension';
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const persistConfig = {
    key: 'chedsk',
    storage,
  }
const loggerMiddleware = createLogger();

const persistedReducer = persistReducer(persistConfig, rootReducer)
 
const composeEnhancers = composeWithDevTools({trace: true, traceLimit: 20});
export const store = createStore(
    persistedReducer,composeEnhancers( applyMiddleware(
        thunkMiddleware,
        loggerMiddleware
    ))
   
)
export const persistor = persistStore(store)


import { store, persistor } from './_helpers/store';
import { PersistGate } from 'redux-persist/integration/react'
render(
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <App />
        </PersistGate>
    </Provider>,
    document.querySelector('#root')
);