Reactjs数据篇

参考代码:GitHub - leellun/zhiqu-web-test2

1 通过createAction创建Action做数据传递

在 Redux 中定义动作的常用方法是分别声明一个动作类型常量和一个动作创建器函数来构造该类型的动作。

store/action.ts

import { createAction } from "@reduxjs/toolkit";const changeChannelAction2 = createAction('changeChannelAction2', (text: string)=> {return {payload: {name:text} as any,}
})
export { changeChannelAction2 };

通过createSlice创建切片状态:store/slice.ts

通过builder.addCase("changeChannelAction2",fn)接收type为changeChannelAction2的数据

import { createSlice } from "@reduxjs/toolkit";const channelSlice = createSlice({name:"channel",initialState:{channel:{name:'3345345'}},reducers:{},extraReducers:(builder)=>{builder.addCase("changeChannelAction2",(state,action:any)=>{console.log("=234=234")state.channel.name=action.payload.name})}
})
const { changeChannel } = channelSlice.actions;
const channelReducer = channelSlice.reducer;
export {changeChannel,channelReducer}

 然后通过dispatch分发数据

 store.dispatch(changeChannelAction2("sdf"))

控制台将会打印

=234=234

2 通过createAsyncThunk异步加载数据,并且传递数据

import { createAsyncThunk } from "@reduxjs/toolkit";const changeChannelAction = createAsyncThunk('changeChannelAction',async (extraInfo: { userId: string }, { dispatch }) => {const { userId } = extraInfo;return userId+"====createAsyncThunk="});export { changeChannelAction };

3  通过createReducer处理数据和状态化数据

import { createReducer } from "@reduxjs/toolkit";const userReducer = createReducer({id:'',name:"sdfsdf"},(builder) => {builder.addCase("changeChannelAction2", (state, action:any) => {console.log(action.payload.name)state.name = action.payload.name;})}
);export default userReducer;

4 多type数据处理状态化

const moreReducer = (state:any, action: any) => {state=action.payloadconsole.log("moreReducer",state)if(state===undefined){return {}}switch (action.type) {case 'changeChannelAction':return state;case 'changeChannelAction2':return state;default:return state;}
};
export default moreReducer;

 5 同步方法指定类型和载体

export function changeUserMsg(payload: any) {return {type: 'changeChannelAction',payload};}store.dispatch(changeUserMsg({name:''}))

 6 异步方法指定类型和载体

export function changeAsyncUserMsg(payload: any) {return async (dispatch:any)=>{dispatch(changeUserMsg(payload))};}

7 获取store中的数据

  const CounterComponent = () => {const name = useSelector((state:any) => {return state.channelReducer.channel.name})return <div>{name}</div>}

8 将store和组件结合

<Provider store={store}></Provider>

 可以在Provider作用访问类使用useDispatcher()

完整代码:

store/action.ts

import { createAction } from "@reduxjs/toolkit";const changeChannelAction2 = createAction('changeChannelAction2', (text: string)=> {return {payload: {id:'',name:text} as any,}
})
export { changeChannelAction2 };

store/reducer.ts

import { createReducer } from "@reduxjs/toolkit";const userReducer = createReducer({id:'',name:"sdfsdf"},(builder) => {builder.addCase("changeChannelAction2", (state, action:any) => {console.log(action.payload.name)state.name = action.payload.name;})}
);export default userReducer;

store/thunk.ts

import { createAsyncThunk } from "@reduxjs/toolkit";const changeChannelAction = createAsyncThunk('changeChannelAction',async (extraInfo: { userId: string }, { dispatch }) => {const { userId } = extraInfo;return userId+"====createAsyncThunk="});export { changeChannelAction };

store/slice.ts 

import { createSlice } from "@reduxjs/toolkit";
import { changeChannelAction } from "./thunk";const channelSlice = createSlice({name:"channel",initialState:{channel:{id:'',name:'3345345'}},reducers:{changeChannel(state, { payload }) {console.log(payload)state.channel = payload;}},extraReducers:(builder)=>{builder.addCase(changeChannelAction.pending, (state, action:any) => {console.log(action.payload,"===1")})builder.addCase(changeChannelAction.fulfilled, (state, action:any) => {console.log(action.payload,"===2")})builder.addCase(changeChannelAction.rejected, (state, action:any) => {console.log(action.payload,"===3")})builder.addCase("changeChannelAction2",(state,action:any)=>{console.log("=234=234")state.channel.name=action.payload.name})}
})
const { changeChannel } = channelSlice.actions;
const channelReducer = channelSlice.reducer;
export {changeChannel,channelReducer}

store/moreReducer.ts

const moreReducer = (state:any, action: any) => {state=action.payloadconsole.log("moreReducer",state)if(state===undefined){return {}}switch (action.type) {case 'changeChannelAction':return state;case 'changeChannelAction2':return state;default:return state;}
};
export default moreReducer;

 store/method.ts

export function changeUserMsg(payload: any) {return {type: 'changeChannelAction',payload};}
export function changeAsyncUserMsg(payload: any) {return async (dispatch:any)=>{dispatch(changeUserMsg(payload))};}

 store/index.ts

import { configureStore } from "@reduxjs/toolkit";
import {changeChannel, channelReducer} from './slice'
import userReducer from './reducer'
import moreReducer from './moreReducer'
const store = configureStore({reducer: {channelReducer,userReducer,moreReducer},devTools: true});export default store;

 app.tsx

import React, { useCallback, useState } from 'react';
import logo from './logo.svg';
import './App.css';
import { Provider, useSelector } from 'react-redux';
import store from './store';
import { changeChannelAction2 } from './store/action';
import { changeChannelAction } from './store/thunk';
import { changeChannel } from './store/slice';
import { changeAsyncUserMsg, changeUserMsg } from './store/method';function App() {const [count, setCount] = useState(0);const handleClick = useCallback(() => {console.log(`Clicked ${count} times`);}, [count]);store.dispatch(changeChannelAction({userId:"234234243"}))store.dispatch(changeChannelAction2("sdf"))store.dispatch(changeChannel({id:"23",name:"test3"}))store.dispatch(changeUserMsg("aaaaaaaaa"))store.dispatch(changeAsyncUserMsg("bbbbbbbb"))const CounterComponent = () => {const name = useSelector((state:any) => {return state.channelReducer.channel.name})return <div>{name}</div>}return (<div className="App"><Provider store={store}><header className="App-header"><img src={logo} className="App-logo" alt="logo" /><p>Edit <code>src/App.tsx</code> and save to reload.</p><aclassName="App-link"href="https://reactjs.org"target="_blank"rel="noopener noreferrer">Learn React</a></header><div>Count: {count}</div><button onClick={() => setCount(count + 1)}>Increment</button><button onClick={handleClick}>Click me</button><CounterComponent/></Provider></div>);
}export default App;

推荐文章:

React进阶系列之数据流 - 掘金 (juejin.cn)

滑动验证页面

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

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

相关文章

力扣刷题学习(跟随视频学着刷)

使用入门 视频链接 【手把手带你刷Leetcode力扣&#xff5c;各个击破数据结构和算法&#xff5c;大厂面试必备技能【已完结】-哔哩哔哩】 https://b23.tv/vIcRT61 时空复杂度 时间&#xff1a; 空间&#xff1a;主要有O(1)和O(n)两种&#xff0c;只用计算开辟的内存&#xff…

三种类的免费SSL证书

目前主流的三种域名证书&#xff1a;单域名证书、多域名证书、通配符泛域名证书。 这三种类型的证书根据用户域名的不同情况&#xff0c;应用场景也大不相同。 单域名证书应用场景&#xff1a; 针对于有且只有一个单独域名的单位&#xff0c;使用单域名证书是刚好能够满足需求…

Linux 高级网络设置

1. rp_filter 逆向路由检查 rp_filter &#xff08;Reverse Path Filtering&#xff09;参数定义了网卡对接收到的数据包进行反向路由验证的规则。他有三个值&#xff0c;0、1、2&#xff0c;具体含意如下&#xff1a; 0&#xff1a;关闭反向路由校验1&#xff1a;开启严格的…

使用脚本定时备份MySql数据库文件

如果mysql不在环境变量中&#xff0c;请先将mysql放入环境变量 #将mysql添加进环境变量中 export PATH$PATH:/usr/local/mysql/bin/#重新加载配置文件 source /etc/profile新建一个脚本 touch backup_all_databases.sh 脚本内容&#xff1a; #!/bin/bash # MySQL登录信息 …

DRF学习之三大认证

一、认证 1、自定义认证 在前面说的 APIView 中封装了三大认证&#xff0c;分别为认证、权限、频率。认证即登录认证&#xff0c;权限表示该用户是否有权限访问接口&#xff0c;频率表示用户指定时间内能访问接口的次数。整个请求最开始的也是认证。 &#xff08;1&#xff…

VUE 打包后 动态修改 后台服务器地址

使用的是第三方 continew-admin 项目 在 continew-admin-ui 项目中 添加 config.json 到public 目录下 {"baseURL": "http://localhost:8000" } 在 request.ts 文件中 async function fetchConfig() {const response await fetch(/config.json);con…

【JavaEE网络】TCP/IP协议:细节与应用

目录 TCP/IP协议协议格式传输层重点协议UDP协议UDP协议端格式 UDP的特点TCP协议TCP协议端格式 TCP的特点 TCP/IP协议 协议格式 应用层&#xff08;后端开发必知必会&#xff09;&#xff1a;这一层也有很多现成的协议&#xff08;后面还会重点介绍HTTP协议&#xff0c;这是做…

SysY 语言

SysY 语言是编译系统设计赛 要实现的编程语言。由 C 语言的一个子集扩展 而成。 每个 SysY 程序的源码存储在一个扩展名为 sy 的文件中。该文件中有且仅 有一个名为 main 的主函数定义&#xff0c;还可以包含若干全局变量声明、常量声明和其 他函数定义。 SysY 语言支持 int/…

jenkins自动化举例

使用 Jenkins 可以显著提高工作效率&#xff1a; 1. **自动化构建**&#xff1a; - 假设您是一个开发人员&#xff0c;需要频繁地编译和测试代码。手动执行这些任务可能会非常耗时。使用 Jenkins&#xff0c;您可以设置自动化构建流程&#xff0c;每当您提交新代码时&#…

RabbitMQ:消息队列的卓越之选

在当今高度互联和数据驱动的世界中&#xff0c;消息队列扮演着至关重要的角色。RabbitMQ&#xff0c;作为其中的佼佼者&#xff0c;以其高效、可靠和灵活的特性&#xff0c;赢得了众多开发者和企业的青睐。本文将深入探讨RabbitMQ的基本概念、核心特性、应用场景以及最佳实践&a…

探秘STM32MDK:编译过程与文件类型解析

探秘STM32MDK&#xff1a;编译过程与文件类型解析 在嵌入式系统开发中&#xff0c;STM32系列微控制器是广泛应用的选择之一&#xff0c;而Keil MDK&#xff08;Microcontroller Development Kit&#xff09;则是一款常用的开发工具套件。了解STM32MDK的编译过程和文件类型对于…

命令执行漏洞【2】vulhub远程命令执行漏洞复现

1.vulhub安装启动靶场环境 &#xff08;1&#xff09;s2-061开启靶场 &#xff08;2&#xff09;s2-059开启靶场 2.漏洞复现 &#xff08;1&#xff09;s2-061漏洞复现 github获取漏洞利用工具 开始利用 &#xff08;2&#xff09;s2-059漏洞复现 在linux特有临时目录/tmp下…

多线程并发和进程通信模拟

一、实验目的&#xff1a; 通过编写多线程并发和进程通信的模拟代码&#xff0c;加深对多线程编程和进程通信的理解。学习如何使用Java中的多线程和管道流来实现并发执行和进程间通信。掌握多线程的基本概念和使用方法&#xff0c;以及进程通信的实现方式。 实验设备与实验环境…

C#实现TFTP客户端

1、文件结构 2、TftpConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace TftpTest {public class TftpConfig{}/// <summary>/// 模式/// </summary>public enum Modes{…

Linux论坛搭建

1.安装httpd服务 1.1安装httpd软件 [rootlocalhost yum.repos.d]# dnf install httpd 1.2.修改httpd的配置 [rootlocalhost yum.repos.d]# vim /etc/httpd/conf/httpd.conf 1.3.启动这个httpd服务,并查看它的状态 [rootlocalhost yum.repos.d]# systemctl start httpd [ro…

NLP(8)--利用RNN实现多分类任务

前言 仅记录学习过程&#xff0c;有问题欢迎讨论 循环神经网络RNN&#xff08;recurrent neural network&#xff09;&#xff1a; 主要思想&#xff1a;将整个序列划分成多个时间步&#xff0c;将每一个时间步的信息依次输入模型&#xff0c;同时将模型输出的结果传给下一个…

JavaEE——spring MVC请求处理

目录 主要目的&#xff1a; 1. Spring web 项目搭建 2. 添加依赖 3. 配置插件 4. 配置设置类 5. 编写controller层类 6. 编写测试的http请求 主要目的&#xff1a; 创建一个spring web项目&#xff1b; 创建控制类&#xff1b; 掌握如何配置MVC&#xff1b; 编写htt…

【机器学习-18】特征筛选:提升模型性能的关键步骤

一、引言 在机器学习领域&#xff0c;特征筛选是一个至关重要的预处理步骤。随着数据集的日益庞大和复杂&#xff0c;特征的数量往往也随之激增。然而&#xff0c;并非所有的特征都对模型的性能提升有所贡献&#xff0c;有些特征甚至可能是冗余的、噪声较大的或者与目标变量无关…

在Visual Studio中查看C项目使用的C语言版本

在Visual Studio中查看C项目使用的C语言版本&#xff0c;可以通过以下步骤进行&#xff1a; 打开Visual Studio。 打开你的C项目。 右键点击项目名称&#xff0c;选择“属性”。 在弹出的属性页中&#xff0c;找到“配置属性” -> “C/C” -> “语言”。 在右侧的“…

(十三)PostgreSQL的扩展(extensions)

PostgreSQL的扩展&#xff08;extensions&#xff09; 基础信息 OS版本&#xff1a;Red Hat Enterprise Linux Server release 7.9 (Maipo) DB版本&#xff1a;16.2 pg软件目录&#xff1a;/home/pg16/soft pg数据目录&#xff1a;/home/pg16/data 端口&#xff1a;5777在Post…