react中redux的详细使用以及持久化处理

一.redux使用

1.安装

npm i  redux

例一:

2.创建redux文件夹,store.js文件

store.js文件

import {legacy_createStore as createStore,combineReducers}from "redux"
// 每一块状态内容对应一个reducer文件
import {CollApsedReducer} from "./CollapsedReducer"
import {LoadingReducer}from "./LoadingReducer"
// combineReducers合并多个reducer
const reducer=combineReducers({CollApsedReducer,LoadingReducer
})
// createStore里面只能放一个reducer,所以上面合并处理一下
const store=createStore(reducer)
export default store

3.将提供者绑定到跟组件内外层,使每个被包裹的组件都可以使用store

import React from 'react';
import IndexRouter from "../src/router"
import {Provider}from "react-redux"
import store from "../src/redux/store"
function App() {return (<Provider store={store}><IndexRouter /></Provider>);
}
export default App;

4.更改状态

import React , { useState }from 'react'
import { Layout,Button ,Avatar, Space,Dropdown } from 'antd';
import {MenuFoldOutlined,MenuUnfoldOutlined,UserOutlined} from '@ant-design/icons';import { useHistory } from 'react-router-dom'import {connect}from "react-redux"
const { Header } = Layout;
// 接收props并使用function TopHeader(props) {console.log(props);// const [collapsed, setCollapsed] = useState(false);const history = useHistory()const isCollapsed=()=>{props.changeCollapsed()}const items = [{key: '1',primary: true,label: '超级管理员',},{key: '2',danger: true,label: '退出登录',},];const onClick = ({ key }) => {  if(key==="2"){localStorage.removeItem("token")history.push({pathname: '/login'})}};return (<Header style={{ padding: 0, }}><Buttontype="text"// 使用仓库的折叠状态icon={props.isCollapsed ? <MenuUnfoldOutlined  /> : <MenuFoldOutlined />}// 更改actiononClick={()=>isCollapsed()}style={{fontSize: '16px',width: 64,height: 64,}}/><div style={{float:'right',marginRight:"20px"}}><span style={{marginRight:"20px"}}>欢迎admin回来</span><Dropdown menu={{ items,onClick}}><a onClick={(e) => e.preventDefault()}><Space><Avatar size="large" icon={<UserOutlined />}  /></Space></a></Dropdown></div></Header>)
}
// 更新props
const mapStateToProps=({CollApsedReducer:{isCollapsed}})=>{return{isCollapsed}
}
// 更新action
const mapDispatchToProps={changeCollapsed(){return {type:"change_collapsed"}}
}
// connect()(组件名)
// connect函数将组件连接到store仓库
export default connect(mapStateToProps,mapDispatchToProps)(TopHeader)

5.使用状态变化的组件

import React, { useState, useEffect } from 'react';
import { useHistory, withRouter } from 'react-router-dom';
import { Layout, Menu } from 'antd';
import { UserOutlined, DesktopOutlined, FileOutlined, PieChartOutlined, TeamOutlined } from '@ant-design/icons';
import "../newssandbox/index.css";
// 引入connect
import {connect}from "react-redux"
const { Sider } = Layout;
const { SubMenu } = Menu;function SideMenu(props) {// props接收const [selectedKey, setSelectedKey] = useState(null);const select=[props.location.pathname.split("/")[1]]const history = useHistory();const onClick = (e) => {history.push(e.key);};useEffect(() => {// 根据路由变化更新选中的菜单项const currentPath = props.location.pathname;setSelectedKey(currentPath);}, [props.location.pathname]);function renderMenuItems(items) {return items.map((item) => {if (item.children) {return (<SubMenu key={item.key} icon={item.icon} title={item.label}>{renderMenuItems(item.children)}</SubMenu>);} else {return (<Menu.Item key={item.key} icon={item.icon}>{item.label}</Menu.Item>);}});}const items = [{key: '/home',label: '首页',icon: <PieChartOutlined />,},{key: 'user-manage',label: '用户管理',icon: <DesktopOutlined />,children: [{ key: '/user-manage/list', label: '用户列表', icon: <DesktopOutlined /> }],},{key: 'right-manage',label: '权限管理',icon: <UserOutlined />,children: [{ key: '/right-manage/role/list', label: '角色列表' },{ key: '/right-manage/right/list', label: '权限列表' }],},{key: 'news-manage',label: '新闻管理',icon: <TeamOutlined />,children: [{ key: '/news-manage/add', label: "撰写新闻" },{ key: '/news-manage/draft', label: '草稿箱' },{ key: '/news-manage/category', label: '新闻分类' }],},{key: 'audit-manage',label: '审核管理',icon: <FileOutlined />,children: [{ key: '/audit-manage/audit', label: "审核新闻" },{ key: '/audit-manage/list', label: '审核列表' },],},{key: 'publish-manage',label: '发布管理',icon: <FileOutlined />,children: [{ key: '/publish-manage/unpublished', label: "待发布" },{ key: '/publish-manage/published', label: '已发布' },{ key: '/publish-manage/sunset', label: '已下线' }],},];return (<div>{/* props.isCollapsed使用 */}<Sider trigger={null} collapsible collapsed={props.isCollapsed}><div className="demo-logo-vertical">全球新闻发布管理系统</div><Menutheme="dark"mode="inline"defaultSelectedKeys={['home']}selectedKeys={[selectedKey]}defaultOpenKeys={select}onClick={onClick}>{renderMenuItems(items)}</Menu></Sider></div>);
}
// {CollApsedReducer:{isCollapsed}}CollApsedReducer reducer文件导出的变量名,isCollapsed状态,此处进行解构
const mapStateToProps=({CollApsedReducer:{isCollapsed}})=>{return{isCollapsed}
}
export default connect(mapStateToProps)(withRouter(SideMenu));

例二:

1.新建LoadingReducer.js文件

export const LoadingReducer=(prevState={loading:false
},action)=>{let {type,payload}=actionswitch (type) {case 'change_loading':// 复制老状态,不可直接修改let newState={...prevState}newState.loading=payloadreturn newState default:return prevState}
}

2.路由文件

import React from 'react'
import {Route,Switch,Redirect}from "react-router-dom"
import Home from "../../views/newssandbox/home/Home"
import UserList from "../../views/newssandbox/user-mange/UserList"    
import RoleList from"../../views/newssandbox/right-manage/RoleList" 
import RightList from"../../views/newssandbox/right-manage/RightList" 
import NoPermission from "../../views/newssandbox/nopermission/Nopermission" 
import NewsAdd from "../../views/newssandbox/news-manage/NewsAdd"
import NewsDraft from "../../views/newssandbox/news-manage/NewsDraft"
import NewsCategory from "../../views/newssandbox/news-manage/NewsCategory"import AuditManage from "../../views/newssandbox/audit-manage/AuditManage"
import AuditList from "../../views/newssandbox/audit-manage/AuditList"import Unpublished from "../../views/newssandbox/publish-manage/Unpublished"import Publishedd from "../../views/newssandbox/publish-manage/Publishedd"
import Sunset from "../../views/newssandbox/publish-manage/Sunset"
import {  Spin } from 'antd';import {connect}from "react-redux"function NewsRouter(props) {return (<div>{/* 为每个页面使用loading功能 */}<Spin size="large" style={{marginTop:"200px"}} spinning={props.loading} ><Switch><Route path="/home" component={Home}/><Route path="/user-manage/list" component={UserList}/><Route path="/right-manage/role/list" component={RoleList}/><Route path="/right-manage/right/list" component={RightList}/><Route path="/news-manage/add" component={NewsAdd}/><Route path="/news-manage/draft" component={NewsDraft}/><Route path="/news-manage/category" component={NewsCategory}/><Route path="/audit-manage/audit" component={AuditManage}/><Route path="/audit-manage/list" component={AuditList}/><Route path="/publish-manage/unpublished" component={Unpublished}/><Route path="/publish-manage/published" component={Publishedd}/><Route path="/publish-manage/sunset" component={Sunset}/>{/* 如果访问根路径回车精确匹配重定向到home页面 */}<Redirect from="/" to="/home" exact/>{/* 如果是随便输入或除了以上路径的其他路径显示404页面 */}<Route path="*" component={NoPermission}/></Switch> </Spin></div>)
}const mapStateToProps=({LoadingReducer:{loading}})=>{return{loading}}const mapDispatchToProps={changeCollapsed(){return {type:"change_loading"}}}
export default connect(mapStateToProps,mapDispatchToProps)(NewsRouter)

3.在axios封装文件内使用

import axios from "axios";
import store from "../redux/store";
axios.defaults.baseURL = "http://localhost:3000";axios.interceptors.request.use((config) => {//  显示loadingstore.dispatch({type: "change_loading",payload: true,});return config;},(error) => {return Promise.reject(error);}
);axios.interceptors.response.use((response) => {//  隐藏loadingstore.dispatch({type: "change_loading",payload: false,});return response;},(error) => {//  隐藏loadingstore.dispatch({type: "change_loading",payload: false,});return Promise.reject(error);}
);export default axios;

二.持久化

1.安装

npm i redux-persist

2.store.js文件配置持久化

import {legacy_createStore as createStore,combineReducers}from "redux"import {CollApsedReducer} from "./CollapsedReducer"
import {LoadingReducer}from "./LoadingReducer"//配置数据的持久化效果
import { persistReducer, persistStore } from "redux-persist";
//导入需要配置的数据源,可以选择,storage,cookie,session等
import storage from "redux-persist/lib/storage";const reducer=combineReducers({CollApsedReducer,LoadingReducer
})
//定义配置的信息
const persitConfig = {// 代表存储名,随便起key:"root",storage,// 如果不想将部分state持久化,也可以将其放入黑名单(blacklist)中,白名单whitelist
//    将loading 模块不做持久化blacklist:["LoadingReducer"]
}
//创建持久化的配置persist的信息
const persistReducers = persistReducer(persitConfig,reducer);
//创建存储对象并且抛出对象
const store=createStore(persistReducers)const persistor =persistStore(store);export{store,persistor}

3.仓库导出方式更改了,组件引入方式要改变

4.根组件内使用PersistGate

import React from 'react';
import IndexRouter from "../src/router"
import {Provider}from "react-redux"
import {store,persistor} from "../src/redux/store"
// 在入口文件中使用 PersistGate 包裹根组件。将延迟渲染app 视图直到持久化状态取回并保存到redux中
import {PersistGate}from "redux-persist/integration/react"
function App() {return (<Provider store={store}><PersistGate loading={null} persistor={persistor}><IndexRouter /></PersistGate></Provider>);
}
export default App;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/62237.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于空洞卷积DCNN与长短期时间记忆模型LSTM的dcnn-lstm的回归预测模型

周末的时候有时间鼓捣的一个小实践&#xff0c;主要就是做的多因子回归预测的任务&#xff0c;关于时序数据建模和回归预测建模我的专栏和系列博文里面已经有了非常详细的介绍了&#xff0c;这里就不再多加赘述了&#xff0c;这里主要是一个模型融合的实践&#xff0c;这里的数…

[论文笔记]DSSM

引言 这是DSSM论文的阅读笔记,后续会有一篇文章来复现它并在中文数据集上验证效果。 本文的标题翻译过来就是利用点击数据学习网页搜索中深层结构化语义模型,这篇论文被归类为信息检索,但也可以用来做文本匹配。 这是一篇经典的工作,在DSSM之前,通常使用传统机器学习的…

博客系统后台控制层接口编写

BlogColumnCon CrossOrigin RequestMapping("/back/blogColumn") RestController public class BlogColumnCon {Autowiredprivate BlogColumnService blogColumnService;/*** 新增** param blogColumn* return*/PostMapping("/add")public BaseResult add…

【自定义物体不受后处理(Volume)影响的组件_Custom Pass Volume】

自定义物体不受后处理影响 "Custom Pass Volume"1. **自定义渲染Custom Pass Volume组件:** 面板如下。2.具体设置如图3.在Frame Debugger视图下是这样的:4.在Frame Debugger带有Custom Pass Volume组件的渲染Pass已经改写成 AfterPostProcess5.记得添加Shader中的…

Docker 的基本概念和优势

Docker 是一种开源的容器化平台&#xff0c;可以轻松部署、管理和运行应用程序。它基于 Linux 容器技术&#xff0c;可以将应用程序和其依赖项打包到一个可移植的容器中&#xff0c;从而使应用程序更易于部署、移植和扩展。 Docker 的主要优势包括&#xff1a; 1. 简化部署&a…

iOS 使用coreData存贮页面的模型数据中的字典

我们使用coreData时候&#xff0c;会遇到较为复杂的数据类型的存贮&#xff0c;例如&#xff0c;我们要存一个模型&#xff0c;但是一个模型里面有个字典&#xff0c;这时候&#xff0c;我们该如何存贮呢 如图所示&#xff0c;一个对象中含有一个字典 我们实现一个公共的方法…

【ArcGIS Pro二次开发】(64):多分式标注

在ArcGIS中有时会遇到需要二分式标注的情况&#xff0c;有时甚至是三分式、四分式。 通过输入标注表达式&#xff0c;可以做出如下的效果&#xff0c;但是代码不短&#xff0c;每次都要输一遍也挺麻烦。 网上也有一些分式标注的python工具&#xff0c;但不够直观&#xff0c;于…

港联证券|股票过户费是什么意思?

股票过户费是指在股票商场中&#xff0c;由于股份所有权的转让&#xff0c;双方需求付出的一种买卖费用。这种费用首要是为了付出证券公司和证券中介机构转让股票所发生的各项费用&#xff0c;如代理费、登记费、买卖税等。股票过户费的数额一般是按照股票的数量和买卖金额来核…

Git学习part1

02.尚硅谷_Git&GitHub_为什么要使用版本控制_哔哩哔哩_bilibili 1.Git必要性 记录代码开发的历史状态 &#xff0c;允许很多人同时修改文件&#xff08;分布式&#xff09;且不会丢失记录 2.版本控制工具应该具备的功能 1&#xff09;协同修改 多人并行不悖的修改服务器端…

rust交叉编译 在mac下编译linux和windows

系统版本macbook proVentura 13.5linux ubuntu22.04.3 LTS/18.04.6 LTSwindowswindows 10 专业版 20H2mac下rustc --versionrustc 1.74.0-nightly (58eefc33a 2023-08-24)查看当前系统支持的交叉编译指定系统版本列表 rustup target list如果已经安装这里会显示(installed)。…

360牛盾点选

网址&#xff1a;https://info.so.com/cache_remove.html 360旗下的产品&#xff0c;协议并不难。 感兴趣的话大家可以去看看&#xff0c;一个AES&#xff0c;坐标需要缩放处理。 鱼导就是牛&#xff0c;还没失败过。 完事儿了哦&#xff0c;大表哥们。以上需要算法&#xff0…

【元宇宙】游戏应用商城对元宇宙的影响

游戏行业不仅是创意设计原则的信息源&#xff0c;还是构建“下一代互联网”的基础技术。它也是元宇宙的经济活动先例。 究竟为什么会认为应用商城设置的30%佣金将导致元宇宙“无法实现”呢&#xff1f;有三个核心原因。首先&#xff0c;应用商城阻止了企业对元宇宙的投资&…

mqtt安卓客户端

1.MQTT&#xff08;消息队列遥测传输协议&#xff09;&#xff0c;是一种基于 发布/订阅 &#xff08;publish/subscribe&#xff09;模式的"轻量级"通讯协议&#xff0c; 该协议构建于TCP/IP协议上 。MQTT最大优点在于&#xff0c;可以以极少的代码和有限的带宽&…

什么是 LSM 思想?它的优缺点都那些?

LSM&#xff08;Log-Structured Merge&#xff09;是一种用于设计和优化存储系统的思想和架构。它最初由闪存文件系统&#xff08;Flash File System&#xff09;和大规模分布式存储系统&#xff08;如 Bigtable 和 HBase&#xff09;采用&#xff0c;并在键值存储引擎中广泛应…

【高阶数据结构】哈希表详解

文章目录 前言1. 哈希的概念2. 哈希冲突3. 哈希函数3.1 直接定址法3.2 除留余数法--(常用)3.3 平方取中法--(了解)3.4 折叠法--(了解)3.5 随机数法--(了解)3.6 数学分析法--(了解) 4. 哈希冲突的解决方法及不同方法对应的哈希表实现4.1 闭散列&#xff08;开放定址法&#xff0…

安全基础 --- https详解(02)、cookie和session、同源和跨域

https详解&#xff08;02&#xff09;--- 数据包扩展 Request --- 请求数据包Response --- 返回数据包 若出现代理则如下图&#xff1a; Proxy --- 代理服务器 &#xff08;1&#xff09;http和https的区别 http明文传输&#xff0c;数据未加密&#xff1b;http页面响应速度…

QT可执行程序打包成安装程序

目录 1.将QT程序先放到一个文件中 2.下载QtInstallerFramework-win-x86.exe 3.将setup.exe单独拷贝出来&#xff0c;进行安装测试 4.测试安装后的程序是否可执行 1.将QT程序先放到一个文件中 &#xff08;1&#xff09;QT切换到release模式&#xff0c;编译后在构建目录生…

C语言函数概述——拜佛代码

函数是一种可重用的代码块&#xff0c;用于执行特定任务或完成特定功能函数作用&#xff1a;对具备相同逻辑的代码进行封装&#xff0c;提高代码的编写效率&#xff0c;实现对代码的重用函数作用演示代码&#xff1a; #include <stdio.h>// 定义函数 void func() {print…

RSA算法与错误敏感攻击

参见《RSA 算法的错误敏感攻击研究与实践》 RSA 算法简介 RSA 算法原理&#xff1a; 1&#xff09; RSA 算法密钥产生过程 &#xff08;1&#xff09;系统随机产生两个大素数 p p p 和 q q q&#xff0c;对这两个数据保密&#xff1b; &#xff08;2&#xff09;计算 n p …

RealSense D455启动教程

环境&#xff1a; ubuntu20.04 ros:noetic 视觉传感器&#xff1a;Intel RealSense D455 通过命令安装不成功后改为下面源码安装 1. 安装Intel RealSense SDK 2.0 1.1源码安装 1. 下载源码git clone https://github.com/IntelRealSense/librealsense cd librealsense…