Reactjs数据篇

server/2024/9/22 16:45:09/

参考代码: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/server/17180.html

相关文章

基于emp的mysql查询

SQL命令 结构化查询语句&#xff1a;Structured Query Language 结构化查询语言是高级的非过程化变成语言&#xff0c;允许用户在高层数据结构上工作。是一种特殊目的的变成语言&#xff0c;是一种数据库查询和程序设计语言&#xff0c;用于存取数据以及查询、更新和管理关系数…

BERT(Bidirectional Encoder Representations from Transformers)

BERT&#xff08;Bidirectional Encoder Representations from Transformers&#xff09;在深度学习中指的是一种基于Transformer架构的预训练模型&#xff0c;特别用于自然语言处理&#xff08;NLP&#xff09;任务。BERT是由Google的研究团队在2018年提出的&#xff0c;并且迅…

Springboot+Vue项目-基于Java+MySQL的IT技术交流和分享平台系统(附源码+演示视频+LW)

大家好&#xff01;我是程序猿老A&#xff0c;感谢您阅读本文&#xff0c;欢迎一键三连哦。 &#x1f49e;当前专栏&#xff1a;Java毕业设计 精彩专栏推荐&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb; &#x1f380; Python毕业设计 &…

[Android]引导页

使用Kotlin Jetpack Compose创建一个左右滑动的引导页, 效果如图. 1.添加依赖项 androidx.compose.ui最新版本查询:https://maven.google.com/web/index.html com.google.accompanist:accompanist-pager最新版本查询:https://central.sonatype.com/ 确保在 build.gradle (M…

数据库服务类--Redis--未授权访问终端Getshell

免责声明:本文仅做技术交流与学习. 目录 前提条件: windows上开启redis服务: Linux上创建&开启redis服务: 操作: 1-连接靶机redis 2-写入webshell 3-访问后门 redis--->webshell Redis未授权访问漏洞复现与利用 - 知乎 (zhihu.com) 前提条件: 端口开放(6379) 目录…

Lock-It for Mac(应用程序加密工具)

OSXBytes Lock-It for Mac是一款功能强大的应用程序加密工具&#xff0c;专为Mac用户设计。该软件具有多种功能&#xff0c;旨在保护用户的隐私和数据安全。 Lock-It for Mac v1.3.0激活版下载 首先&#xff0c;Lock-It for Mac能够完全隐藏应用程序&#xff0c;使其不易被他人…

SQLite FTS5 扩展(三十)

返回&#xff1a;SQLite—系列文章目录 上一篇:SQLite的知名用户(二十九) 下一篇:SQLite 的命令行 Shell(三十一&#xff09; 1. FTS5概述 FTS5 是一个 SQLite 虚拟表模块&#xff0c;它为数据库应用程序提供全文搜索功能。在最基本的形式中&#xff0c; 全文搜索引擎允许…

nvm管理多个node版本,快速来回切换node版本

前言 文章基于 windows环境 使用nvm安装多版本nodejs。 最近公司有的项目比较老需要降低node版本才能运行&#xff0c;由于来回进行卸载不同版本的node比较麻烦&#xff1b;所以需要使用node工程多版本管理&#xff0c;后面自己就简单捯饬了一下nvm来管理node&#xff0c;顺便…