React整合redux并开启持久化

React整合redux并开启持久化

一、添加相关依赖

yarn add redux                                        # 增加redux
yarn add react-redux
yarn add @babel/plugin-proposal-decorators            # 开启注解的支持
yarn add babel-plugin-transform-decorators-legacy
yarn add redux-persist                                # redux中数据的持久化
yarn add redux-devtools-extension                     # 用于在浏览器查询redux数据的工具     

二、整合redux

下面是我最后整合好的redux的相关的文件和需要修改的部分,我们一个个的看。
在这里插入图片描述

2.1. redux模块示例代码

这里的constant.js文件是用于添加一些静态变量的:

// 登陆用户信息
export const ADMIN_LOGIN_USER_INFO = "admin_login_user_info"
export const HOME_ARTICLE_PARAMS = "home_article_params";
export const HOME_ARTICLE_CATEGORY = "home_article_category"
export const HOME_ARTICLE_DEL_PARAMS = "home_article_del_params" 

models文件下的js文件表示各个模块对应的store中的数据:

import {ADMIN_LOGIN_USER_INFO} from "../constant";

// user模块中store的初始化数据
const userInitData = {
    id: '',
    username: '',
    brief: '',
    email: '',
    token: '',
    status: false
}

// 这个函数是根据不同的active返回不同数据
export default function userReducer(state = userInitData, action) {
    const {type, data} = action;
    switch (type) {
        case ADMIN_LOGIN_USER_INFO:
            return {
                ...state,
                ...data
            }
        default:
            return state
    }
}

而对于active文件夹的数据是各个模块的操作数据的方法:

import {ADMIN_LOGIN_USER_INFO} from "../constant";

// 设置用户的登陆信息
export const setUserInfo = data => ({type: ADMIN_LOGIN_USER_INFO, data})
2.2. store整合持久化
import {combineReducers, createStore } from 'redux'
import userReducer from "./models/user";
import storage from 'redux-persist/lib/storage'
import {persistReducer, persistStore} from "redux-persist";
import {composeWithDevTools} from "redux-devtools-extension";

// 将所有模块的store的数据汇总
const allReducer = combineReducers({
    user: userReducer
})

// 配置持久化的key, 这里默认使用loacl storage 做持久化的
const persistConfig = {
    key: 'blog',
    storage: storage 
}

const persistedReducer = persistReducer(persistConfig, allReducer);

// 将redux插件绑定到store上
export const store = createStore(persistedReducer, composeWithDevTools())
// 构建持久化
export const persis = persistStore(store)
2.3. index修改
import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter, Route, Switch} from "react-router-dom";
import {persis, store} from './redux/index'
import AdminLayout from "./pages/admin";
import {Provider} from "react-redux";
import {PersistGate} from "redux-persist/integration/react";

ReactDOM.render(
    <Provider store={store} >   // redux标签
        <PersistGate loading={null} persistor={persis}>   // 持久化标签
            <BrowserRouter>
                <Switch>
                    <Route path="/admin" render={routeProps => <AdminLayout {...routeProps} />} />
                </Switch>
            </BrowserRouter>
        </PersistGate>
    </Provider>,
    document.getElementById('root')
);
2.4. 支持注解的配置

这里使用的craco进行配置项目的管理。

const path = require('path')
const resolve = (dir) => path.join(__dirname, '.', dir)
const CracoLessPlugin = require('craco-less');

module.exports = {
    plugins: [
        {
            plugin: CracoLessPlugin,
            options: {
                lessLoaderOptions: {
                    lessOptions: {
                        modifyVars: {
                            '@primary-color': "#1DA57A",
                            "@link-color": "#1DA57A",
                            "@border-radius-base": "2px"
                        },
                        javascriptEnabled: true,
                    },
                },
                cssLoaderOptions: {                    // css模块化
                    modules: {
                        localIdentName: '[local]_[hash:base64:5]',
                        // 回调必须返回 `local`,`global`,或者 `pure`
                        mode: (resourcePath) => {
                            if (/pure\.(less|css)$/i.test(resourcePath)) {
                                return 'pure'
                            }

                            if (/(global)\.(less|css)$/i.test(resourcePath)) {
                                return 'global'
                            }

                            if (/antd/i.test(resourcePath)) {
                                return 'global'
                            }

                            return 'local'
                        },
                    },
                },
                babelPluginImportOptions: {
                    libraryName: 'antd',
                    libraryDirectory: 'es',
                    style: true,
                },
            },
        },
    ],
    webpack: {
        alias: {
            '@': resolve('src')
        }
    },
    babel: {
        plugins: [
            [
                '@babel/plugin-proposal-decorators',   // 增加对于注解的支持
                { 
                    legacy: true
                }
            ]
        ]
    }
};
2.5. 提示

关于上面对redux的理解完全是为了好记,具体看官方文档就可以。

三、使用

在react的组件上使用注解@connect,具体代码如下:

import {connect} from "react-redux";

@connect(
    state => state.user   // 拿到redux中use部分
)
class AdminLayout extends React.Component {

    render() {
        console.log("用户信息", this.props);
        const { status } = this.props;
        return (
            <ConfigProvider locale={zhCN}>   // 这里做鉴权判断
                <Switch>
                    {
                        !status ? <Route path="/admin/login" render={routers => <AdminLogin {...routers} />} />:
                            <Route path="/admin" render={routers => <AdminContent {...routers} />} />
                    }
                    <Redirect to="/admin/login" form="/admin/*" />
                </Switch>
            </ConfigProvider>
        )
    }
}

export default AdminLayout;   // 这里需要最后导出组件

接着看一下持久化的数据:
在这里插入图片描述

最后观察一下redux插件的使用情况:
在这里插入图片描述

React Redux中实现数据持久化有多种方法,下面是其中一种常用的方法: 1. 使用redux-persist库:redux-persist是一个用于实现Redux数据持久化的第三方库。它通过将Redux store中的数据保存到本地存储(如localStorage或sessionStorage)中,以便在刷新页面或重新加载应用程序时保持数据的持久性。 首先,安装redux-persist库: ``` npm install redux-persist ``` 然后,在Redux配置文件中,进行redux-persist的配置和初始化: ```javascript import { createStore } from 'redux'; import { persistStore, persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; // 默认使用localStorage // 导入你的reducer import rootReducer from './reducers'; // 配置redux-persist const persistConfig = { key: 'root', // 存储的key,默认为root storage, // 使用的存储引擎,默认为localStorage }; const persistedReducer = persistReducer(persistConfig, rootReducer); // 创建store const store = createStore(persistedReducer); const persistor = persistStore(store); export { store, persistor }; ``` 最后,在应用程序的入口文件中,使用`PersistGate`组件包裹整个应用程序,并将`persistor`作为其属性: ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { PersistGate } from 'redux-persist/integration/react'; import { store, persistor } from './store'; ReactDOM.render( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> // 应用程序的根组件 </PersistGate> </Provider>, document.getElementById('root') ); ``` 使用以上配置Redux的状态将会被自动保存到本地存储中,并在应用程序重新加载时被恢复。你可以根据需要自行调整配置,例如设置存储引擎、存储的key等。详细的配置和更多高级用法,请参考redux-persist库的官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值