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插件的使用情况: