Reactjs数据篇

devtools/2024/10/21 17:22:21/

参考代码: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.ppmy.cn/devtools/16718.html

相关文章

Python内存管理与垃圾回收机制深度解析

Python内存管理与垃圾回收机制深度解析 在Python编程中&#xff0c;内存管理是一项至关重要的任务。与其他一些编程语言不同&#xff0c;Python提供了自动内存管理功能&#xff0c;程序员无需显式地分配和释放内存。这一特性大大简化了编程过程&#xff0c;减少了内存泄漏等问…

发布自己的npm包

注册账号 首先需要先到npm官网注册个账号&#xff0c;https://www.npmjs.com 。 注意&#xff0c;邮箱需要认证&#xff0c;否则上传包的时候就会报错。 关联​ 接下来打开powershell(cmd等皆可)&#xff0c;关联npm账号&#xff0c; 按照提示依次输入注册的信息&#xff…

【每日力扣】240. 搜索二维矩阵 II与48. 旋转图像

&#x1f525; 个人主页: 黑洞晓威 &#x1f600;你不必等到非常厉害&#xff0c;才敢开始&#xff0c;你需要开始&#xff0c;才会变的非常厉害 240. 搜索二维矩阵 II] 编写一个高效的算法来搜索 *m* x *n* 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性&#xff…

【C++】---STL之list的模拟实现

【C】---STL之list的模拟实现 一、list模拟实现思路二、结点类的实现三、list迭代器的实现1、ListIterator类2、构造函数3、operator*运算符重载5、operator->运算符重载6、operator&#xff01;运算符重载7、operator运算符重载8、前置9、后置10、前置--11、后置-- 四、lis…

Apache Doris 基于 Workload Group 的负载隔离能力解读|Deep Dive

作者&#xff1a;SelectDB 技术团队 现如今企业的数据查询需求在不断增多&#xff0c;在共享同一集群时&#xff0c;往往需要同时面对多个业务线或多种分析负载的并发查询。在有限的资源条件下&#xff0c;查询任务间的资源抢占将导致性能下降甚至集群不稳定&#xff0c;因此负…

文化旅游3D数字孪生可视化管理平台推动文旅产业迈向更加美好的未来

随着数字化、智能化管理成为文旅产业发展的必然趋势&#xff0c;数字孪生公司深圳华锐视点创新性地推出了景区三维可视化数字孪生平台&#xff0c;将线下的实体景区与线上的虚拟世界完美融合&#xff0c;引领智慧文旅新潮流。 我们运用先进的数字孪生、web3D开发和三维可视化等…

内联函数、带默认形参值的函数、引用传参以及函数重载的具体介绍和例子

内联函数 使用函数有利于代码重用&#xff0c;可以提高开发效率&#xff0c;增强程序的可靠性&#xff0c;也便于分工合作&#xff0c;便于修改维护。但是&#xff0c;函数调用也会降低程序的执行效率&#xff0c;增加时间和空间方面的开销。因此对于一些功能简单、规模较小又…

【Vue】通过Axios实现异步通信(简单案例)

一、Axios介绍 1、是什么 Axios 是一个基于 promise 的 HTTP 库&#xff0c;简单的讲就是可以发送get、post请求。当然这些请求ajax和jquery也能做&#xff0c;但是由于Vue、React等框架的出现&#xff0c;促使了Axios轻量级库的出现&#xff0c;因为Vue等&#xff0c;不需要操…