React之redux的数据持久化存储
我们在使用 redux 的时候,发现有个问题,就是刷新页面后,数据会丢失,这时候我们希望数据能持久化存储,而 redux 中刚好有这样一款中间件,能够持久化保存数据,它就是 redux-persist。
1、安装中间件 redux-persist
npm install redux-persist
1
2、配置 persistStore 和 persistReducer
// /src/react-redux/index.js
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // 默认是localStorage存储
//import storageSession from 'redux-persist/lib/storage/session'; //存储到sessionStorage
import countReducer from './reducers/countReducer';
import studentReducer from "./reducers/studentReducer"
// 设置持久化配置
const persistConfig = {
key: "my-redux", // key是必须要配置的
storage, // 选择存储方式,localStorage还是sessionStorage
whitelist: ["countReducer", "studentReducer"], // 选择需要持久化存储的数据
blacklist: [], // 配置黑名单,选择不需要持久化存储的数据
}
/*
合并reducer,将多个reducer函数合并为一个最终的 reducer 函数
*/
const rootReducer = combineReducers({
countReducer,
studentReducer
})
// 创建持久化reducer
const persistedReducer = persistReducer(persistConfig, rootReducer)
// 使用configureStore方法创建store配置如下:
export const store = configureStore({
reducer: persistedReducer,
// 关闭redux序列化检测,否则会报错,类似A non-serializable value was detected in an action
middleware: (getDefaultMiddleware) => getDefaultMiddleware({
serializableCheck: false
})
})
// 使用createStore方法创建store配置如下,此时需要从redux中引入createStore:
// export const store = createStore(persistedReducer)
export const persistor = persistStore(store)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
3、在项目根目录下的 index.js 中配置如下
import React, {StrictMode} from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/integration/react'
import { persistor, store } from "./reactRedux/index"
ReactDOM.render(
<StrictMode>
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
</StrictMode>,
document.getElementById('root')
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
至此,数据持久化存储就搞定了
编辑 (opens new window)
上次更新: 7/1/2024, 4:56:33 PM