- 在React项目实际开发中,我们常常会对一些数据进行存储缓存中,防止用户刷新浏览器,数据丢失问题,比如token,用户信息之类的。之前都是手写一遍localStorage和sessionStorage储存,接来下,我们通过一个插件
redux-persist
配置项,来存储数据。
存储数据配置
cnpm install redux-persist
- store文件配置
- 本地存储
import storage from 'redux-persist/lib/storage
- 会话存储
import storageSession from 'redux-persist/lib/storage/session
- 其中
blacklist
设置哪些数据不需要存储,因为在项目中,有些数据是没有必要存储的
import { createStore,combineReducers,applyMiddleware,compose } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from "redux-persist/lib/storage";
import language from './language/languageReducer'
const allReducer = {
language
}
const persistConfig = {
key: "root",
storage,
whitelist: ["language"],
blacklist:[],
}
const rootReducer = combineReducers(allReducer)
const persistedReducer = persistReducer(persistConfig, rootReducer)
const store = createStore(persistedReducer,compose(window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()))
export const persistor = persistStore(store)
export default store
使用PersistGate包装您的根组件
import store, {persistor} from './redux/store'
import { PersistGate } from "redux-persist/integration/react";
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
- 以上就是在redux解决数据丢失问题
- 如果想看react中英文切换,移步到 点击跳转: link.