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.payload
  console.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.payload
  console.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>
        <a
          className="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.mfbz.cn/a/575204.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

庐山研习班上介绍的25个LINUX工具

从2013年的第一届算起&#xff0c;庐山研习班走过十余个年头&#xff0c;办了十几次了。但每一次&#xff0c;都有很多不一样。即使是相同的主题&#xff0c;也有很大差异。 今年春季的庐山研习班是在上个周末。周四晚上我和大部分同学都到了五老峰脚下的训练基地。 除了周六下…

【可下载】CDA 1级教材《精益业务数据分析》2023最新版

CDA一级认证教材&#xff1a;《精益业务数据分析》 全面、系统地讲述业务描述性分析为企业决策行为创造价值的全流程技能&#xff0c;涵盖描述性数据分析方法、业务分析方法、数据分析结果应用方法等内容。 条理清晰的结构、通俗易懂的语言、完整立体的知识框架为读者铺开一幅…

Vite 热更新(HMR)原理了解一下

❝ 幸福的三大要素是&#xff1a;有要做的事&#xff08;something to do&#xff09;、有要爱的人&#xff08;someone to love&#xff09;、有寄予希望的东西&#xff08;something to hope for&#xff09; ❞ 大家好&#xff0c;我是「柒八九」。一个「专注于前端开发技术…

CK_Label_V15

CK_Label_v15&#xff08;外接供电版&#xff09; 产品型号 CK_Label_v15 尺寸 63*14.6*7.9mm 按键 0 指示灯 1 RGB&#xff08;7种(红/绿/蓝/黄/紫/白/青)&#xff09; 通信方式 无线通信 工作频段 868MHz 供电方式 24V外接供电 电池容量 300mAh 电池寿命 …

第⑰讲:Ceph集群各组件的配置参数调整

文章目录 1.Ceph集群各组件的配置文件1.1.Ceph各组件配置方式1.2.ceph临时查看、修改配置参数的方法 2.调整Monitor组件的配置参数删除Pool资源池2.1.临时调整配置参数2.2.永久修改配置参数 1.Ceph集群各组件的配置文件 1.1.Ceph各组件配置方式 Ceph集群中各个组件的默认配置…

IDEA中配置使用maven和配置maven的中央仓库

1 以汉化后的IDEA为例配置maven 打开idea选择文件 选择 设置 点击>构建.执行.部署 点击>构建工具 点击>Maven 其中Maven主路径 就是我们maven下载解压后的路径 可以通过边上的三个点选择你解压后的绝对路径&#xff0c;也可以直接把解压后的绝对路劲复制过来 以下…

从零开始,快速掌握创建百度百科技巧

百科是一种常用的知识库&#xff0c;对于想要分享或搜索相关知识的人们来说&#xff0c;它是一个必备的工具。而如何创建一个百科呢&#xff1f;下面将详细介绍创建百科的步骤和技巧&#xff0c;帮助你轻松掌握创建百科的方法。 首先&#xff0c;创建百科需要明确一个主题或领域…

Gin+WebSocket实战——在线聊天室WebSocketDemo详细使用教程

文章目录 仓库地址项目简介如何使用 仓库地址 Github&#xff1a;https://github.com/palp1tate/WebsocketDemo 欢迎star&#xff01;&#x1f60e; 项目简介 利用 GinWebSocket 实现的在线聊天室Demo项目&#xff0c;支持加入/离开聊天室广播、给其他用户发送消息等。 如何…

day04 51单片机-矩阵按键

1 矩阵按键 1.1 需求描述 本案例实现以下功能&#xff1a;按下矩阵按键SW5到SW20&#xff0c;数码管会显示对应的按键编号。 1.2 硬件设计 1.2.1 硬件原理图 1.2.2 矩阵按键原理 1.3软件设计 1&#xff09;Int_MatrixKeyboard.h 在项目的Int目录下创建Int_MatrixKeyboard…

OpenCV 实现霍夫圆变换

返回:OpenCV系列文章目录&#xff08;持续更新中......&#xff09; 上一篇&#xff1a;OpenCV实现霍夫变换 下一篇:OpenCV 实现重新映射 目标 在本教程中&#xff0c;您将学习如何&#xff1a; 使用 OpenCV 函数 HoughCircles()检测图像中的圆圈。 理论 Hough 圆变换 H…

Mysql 、Redis 数据双写一致性 更新策略与应用

零、important point 1. 缓存双写一致性问题 2. java实现逻辑&#xff08;对于 QPS < 1000 可以使用&#xff09; public class UserService {public static final String CACHE_KEY_USER "user:";Resourceprivate UserMapper userMapper;Resourceprivate Re…

javascript使用setTimeout函数来实现仅执行最后一次操作

在JavaScript中&#xff0c;setTimeout函数用于在指定的毫秒数后执行一个函数或计算表达式。它的主要用途是允许开发者延迟执行某些代码&#xff0c;而不是立即执行。 当我们想要确保仅最后一次更新UI时&#xff0c;我们可以使用setTimeout来合并多次连续的更新请求。具体做法…

C++11 数据结构7 队列的链式存储,实现,测试

前期考虑 队列是两边都有开口&#xff0c;那么在链式情况下&#xff0c;线性表的链式那一边作为对头好呢&#xff1f; 从线性表的核心的插入和删除算法来看&#xff0c;如果在线性表链表的头部插入&#xff0c;每次循环都不会走&#xff0c;但是删除的时候&#xff0c;要删除线…

回归与聚类——K-Means(六)

什么是无监督学习 一家广告平台需要根据相似的人口学特征和购买习惯将美国人口分成不同的小 组&#xff0c;以便广告客户可以通过有关联的广告接触到他们的目标客户。Airbnb 需要将自己的房屋清单分组成不同的社区&#xff0c;以便用户能更轻松地查阅这些清单。一个数据科学团队…

Python爱心代码

爱心效果图&#xff1a; 完整代码&#xff1a; import random from math import sin, cos, pi, log from tkinter import *# 定义画布尺寸和颜色 CANVAS_WIDTH 640 CANVAS_HEIGHT 480 CANVAS_CENTER_X CANVAS_WIDTH / 2 CANVAS_CENTER_Y CANVAS_HEIGHT / 2 IMAGE_ENLARG…

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{…

大模型都在用的:旋转位置编码

写在前面 这篇文章提到了绝对位置编码和相对位置编码&#xff0c;但是他们都有局限性&#xff0c;比如绝对位置编码不能直接表征token的相对位置关系&#xff1b;相对位置编码过于复杂&#xff0c;影响效率。于是诞生了一种用绝对位置编码的方式实现相对位置编码的编码方式——…

LS2K1000LA基础教程

基于LS2K1000LA的基础教程 by 南京工业大学 孙冬梅 于 2024.4.25 文章目录 基于LS2K1000LA的基础教程一、目的二、平台1.硬件平台2.软件平台 三、测试0.开发板开机及编译器配置0.1 开发板控制台0.2 虚拟机编译器配置 1. 简单应用编程1.helloworld.c2. fileio 文件操作3.proce…

Scrapy 爬虫教程:从原理到实战

Scrapy 爬虫教程&#xff1a;从原理到实战 一、Scrapy框架简介 Scrapy是一个由Python开发的高效网络爬虫框架&#xff0c;用于从网站上抓取数据并提取结构化信息。它采用异步IO处理请求&#xff0c;能够同时发送多个请求&#xff0c;极大地提高了爬虫效率。 二、Scrapy运行原…

入坑 Java

原文&#xff1a;https://blog.iyatt.com/?p11305 前言 今天&#xff08;2023.8.31&#xff09;有个学长问我接不接一个单子&#xff0c;奈何没学过 Java&#xff0c;本来不打算接的。只是报酬感觉还不错&#xff0c;就接了。 要求的完成时间是在10月初&#xff0c;总共有一…
最新文章