react中使用redux-persist做持久化储存

某天下午折腾着玩的 – 笔记

安装相关依赖

npm install @reduxjs/toolkit redux-persist redux react-redux
// store.jsx
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // 选择持久化存储引擎,如 localStorage 或 AsyncStorage

import rootReducer from "./reducers/index"; // 导入您的根 reducer

// 配置持久化设置
const persistConfig = {
  key: "root", // 存储的键名
  storage, // 持久化存储引擎
  // 可选的配置项,如白名单、黑名单等 选其一就好了
  // blacklist:['test'], // 只有 test 不会被缓存
  // whitelist: ["test"], // 只有 test 会被缓存
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware({
    serializableCheck: false, // 禁用严格模式
  }),
});

const persistor = persistStore(store);

export { store, persistor };

将 store 提供给应用程序:将 Redux store 提供给根组件,以便在整个应用程序中可以访问到 Redux 状态

// main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { store, persistor } from "./redux/store";
import App from "./App";

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>
);

reducer 示例:

// reducers/index.jsx
import { combineReducers } from "redux";
import userReducer from "./user";
import baseReducer from "./base";

const rootReducer = combineReducers({
  user: userReducer,
  base: baseReducer,
});

export default rootReducer;
// reducers/user.jsx
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  token: "默认值token",
  isLogin: false,
};

const user = createSlice({
  name: "user",
  initialState,
  reducers: {
    setToken: (state, action) => {
      // 将传入的值设置为 token 的新值
      state.token = action.payload;
    },
  },
});

export const { setToken } = user.actions;
export default user.reducer;

在组件中使用

// App.jsx
import { useSelector, useDispatch } from "react-redux";
import { setToken } from "./redux/reducers/user";

const App = () => {
  const user = useSelector((state) => state.user);
  // 在页面组件中使用 useDispatch 获取 dispatch 函数,用于派发 action
  const dispatch = useDispatch();
  const setTokenFun = () => {
    dispatch(setToken("一个新的token"));
  };
  
  return (
    <>
      <p>token====={user.token}</p>
      <Button type="primary" onClick={setAddressFun}>
        Set Token
      </Button>
    </>
  );
};

export default App;

你可能感兴趣的:(react.js,redux-persist,持久化储存)