react redux用法学习

参考资料:
https://www.bilibili.com/video/BV1ZB4y1Z7o8
https://cn.redux.js.org/tutorials/essentials/part-5-async-logic
AI工具:deepseek,通义灵码

第一天

安装相关依赖:
使用redux的中间件:

npm i react-redux

react-redux 并不是另一个 redux,而是对 redux 做了封装

在这里插入图片描述

npm i @reduxjs/toolkit

更好的使用 react-redux 的工具

构建目录
在这里插入图片描述
示例代码

index.js


import { configureStore } from "@reduxjs/toolkit";

import channelReducer from "./modules/channelStore";

const store = configureStore({
  reducer: {
    channelReducer: channelReducer,
  }
})

export default store;

modules/xxx.js

import { createSlice } from "@reduxjs/toolkit";

import { getStoreList } from "../../utils/http";

const counterSlice = createSlice({
  name: "counter",
  initialState: {
    channelList: [],  
  },
  reducers: {
    setChannel(state, action) {
      // 不能计算随机值,因为reducer是纯函数,不能有副作用
      state.channelList = action.payload
    },
    setChannel1: {
      reducer(state, action) {
        console.log("state -- ", state)
        console.log("action -- ", action)
        // state.push(action.payload)
      },
      prepare(title, content) {
        console.log("title -- ", title)
        console.log("content -- ", content)
        return {
          payload: {
            id: 1,
            title,
            content
          }
        }
      }
    }
  }
})

const { setChannel, setChannel1 } = channelSlice.actions

// 方法1
const fetchChannlList = async (dispatch) => {
  const response = await getStoreList()
  dispatch(setChannel(response.data.businessList))
}

// 方法2
const fetchChannlList2 = () => async (dispatch) => {
  dispatch(setChannel1(1, 2))
  // const response = await getStoreList()
  // dispatch(setChannel(response.data.businessList))
}

export {
  fetchChannlList,
  fetchChannlList2
};

const reducer = channelSlice.reducer;

export default reducer;

xxx.js为 modules 内独立redux模块
reducer内不要有类似生成随机数的逻辑,保证纯函数
reducers内的reducer可以是函数写法,也可以对象写法。对象写法会有reducer 与 prepare这两个回调函数可供使用。
prepare为该 setChannel1 获取的参数的收束,可在其中加工参数,生成随机数return
reducer为该 setChannel1 原参数,state、action

xxx.jsx

import { useSelector, useDispatch } from "react-redux";
import { useEffect } from 'react';

import styles from './demo.module.css'

import {
  fetchChannlList,
  fetchChannlList2
} from '../../store/modules/channelStore'

const Demo = () => {
  const {channelList} = useSelector(state => state.channelReducer);
  const dispatch = useDispatch();
  useEffect(() => {
      // 方法1
    fetchChannlList(dispatch)
    
    // 方法2
    dispatch(fetchChannlList2())
  }, [])
  return (
    <div>
      <h1>Hello World1</h1>
      <p>Hello World</p>
      <ul>
        {
          channelList.map(item => {
            return <li key={item.businessId}>{item.storeName}</li>
          })
        }
      </ul>
    </div>
  )
}

export default Demo;

其中 useSelector 可获取 redux 的 state,useDispatch 可触发 redux 的 action 修改 state。

代码中 方法2 是官网推荐方法,及将reducer的action引到jsx后,将方法放到dispatch里调用,reducer的异步方法为:

const fetchChannlList2 = () => async (dispatch) => {
  // dispatch(setChannel1(1, 2))
  const response = await getStoreList()
  dispatch(setChannel(response.data.businessList))
}

其中dispatch会在第二次回调中给出来

而 方法1 是我尝试使用的,reducer的异步方法为:

const fetchChannlList = async (dispatch) => {
  const response = await getStoreList()
  dispatch(setChannel(response.data.businessList))
}

fetchChannlList 直接就拿到了dispatch
目前得到的结果都是一致的
后续学习中再寻找方法2 比 方法1 更推荐的原因。

反思问题

为什么 reducer 不能生成随机数,在我多次实验与查询后,生成随机数可能会有一下影响:

1.无法做test,没办法做断言测试(纯函数可做断言)
2.reducer中产生随机数可能导致组件多次更新,消耗更多性能
3.使用谷歌tool的时间旅行时,如果reducer中使用类似随机数逻辑可能导致 tool无法定位问题

第二天

就上述问题:方法2 比 方法1 更推荐的原因

      // 方法1
    fetchChannlList(dispatch)
    
    // 方法2
    dispatch(fetchChannlList2())

当使用方法1时,下面reducer只会触发reducer,而不会走prepare的逻辑
而当使用方法2时,入参会先进入prepare后通过return,进入reducer

    setChannel1: {
      reducer(state, action) {
        console.log("state -- ", state)
        console.log("action -- ", action)
        // state.push(action.payload)
      },
      prepare(title, content) {
        console.log("title -- ", title)
        console.log("content -- ", content)
        return {
          payload: {
            id: 1,
            title,
            content
          }
        }
      }
    }

未完待续

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

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

相关文章

【2025 Unity Meta Quest MR 开发教程】透视 Passthrough 模块配置(戴上头显看见现实画面)

XR 开发者社区&#xff1a;https://www.spatialxr.tech/ 文章目录 &#x1f4d5;导入透视模块&#x1f4d5;OVRManager&#x1f4d5;OVRPassthroughLayer 脚本&#x1f4d5;相机 教程中使用的 SDK&#xff1a;Meta XR SDK v72&#xff08;可以从 Unity 资源商店添加 Meta XR A…

UWB功耗大数据插桩调研

一、摘要 UWB功耗点 插桩点 日志关键字 电流 蓝牙持锁 BatteryStats的锁统计 vendor_bluetooth_lock 30~40mA 测距 UwbSessionManager.startRanging UwbSessionManager.stoptRanging 或接入fadiKey Uwb状态广播 "com.fadiui.dkservice.action.uwb.state.change&q…

旅游行业内容管理系统CMS提升网站建设效率与体验

内容概要 在如今快速发展的互联网时代&#xff0c;旅游行业对网站的要求越来越高&#xff0c;内容管理系统&#xff08;CMS&#xff09;的应用不可或缺。以 Baklib 为代表的先进CMS可显著提高旅游网站的建设效率与用户体验。为了满足不断变化的市场需求&#xff0c;这些系统通…

【vscode+latex】实现overleaf本地高效编译

overleaf本地高效编译 1. 配置本地latex环境2. vscode插件与配置3. 使用 之前觉得用overleaf在线写论文很方便&#xff0c;特别是有辅助生成latex格式公式的网页&#xff0c;不需要在word上一个一个手打调格式。 然而&#xff0c;最近在写一篇论文的时候&#xff0c;由于这篇论…

消费电子产品中的噪声对TPS54202的影响

本文章是笔者整理的备忘笔记。希望在帮助自己温习避免遗忘的同时&#xff0c;也能帮助其他需要参考的朋友。如有谬误&#xff0c;欢迎大家进行指正。 一、概述 在白色家电领域&#xff0c;降压转换器的应用非常广泛&#xff0c;为了实现不同的功能就需要不同的电源轨。TPS542…

51c自动驾驶~合集49

我自己的原文哦~ https://blog.51cto.com/whaosoft/13164876 #Ultra-AV 轨迹预测新基准&#xff01;清华开源&#xff1a;统一自动驾驶纵向轨迹数据集 自动驾驶车辆在交通运输领域展现出巨大潜力&#xff0c;而理解其纵向驾驶行为是实现安全高效自动驾驶的关键。现有的开…

IGBT的两级关断

IGBT&#xff08;绝缘栅双极型晶体管&#xff09;的两级关断&#xff08;Two-stage turn-off&#xff09;是一种优化关断过程的方法&#xff0c;主要用于减少关断时的电压过冲和dv/dt&#xff08;电压变化率&#xff09;过高的问题&#xff0c;特别是在大功率应用中&#xff08…

centos 7 关于引用stdatomic.h的问题

问题&#xff1a;/tmp/tmp4usxmdso/main.c:6:23: fatal error: stdatomic.h: No such file or directory #include <stdatomic.h> 解决步骤&#xff1a; 1.这个错误是因为缺少C编译器的标准原子操作头文件 stdatomic.h。在Linux系统中&#xff0c;我们需要安装开发工具…

20250211解决荣品的RK3566核心板在Android13下出现charge_extrem_low_power的问题

20250211解决荣品的RK3566核心板在Android13下出现charge_extrem_low_power的问题 2025/2/11 17:45 缘起&#xff1a;荣品的RK3566核心板在Android13下&#xff0c;出现charge_extrem_low_power之后就直接挂住了。 由于我司使用了CW2217这个电量计&#xff0c;没有使用核心板自…

动手学深度学习---深层神经网络

目录 一、神经网络1.1、模型训练1.2、损失函数1.2.1、分类&#xff1a;hinge loss/合页损失/支持向量机损失1.2.2、分类&#xff1a;交叉熵损失(softmax分类器)1.2.2.1 二分类交叉熵损失1.2.2.2 多分类交叉熵损失 1.2.3、回归&#xff1a;误差平方和&#xff08;SSE&#xff09…

(定时器,绘制事件,qt简单服务器的搭建)2025.2.11

作业 笔记&#xff08;复习补充&#xff09; 1> 制作一个闹钟软件 头文件 #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QPushButton> //按钮类 #include <QTimer> //定时器类 #include <QTime> //…

STM32_USART通用同步/异步收发器

目录 背景 程序 STM32浮空输入的概念 1.基本概念 2. STM32浮空输入的特点 3. STM32浮空输入的应用场景 STM32推挽输出详解 1. 基本概念 2. 工作原理 3. 应用场景 使能外设时钟 TXE 和 TC的区别 USART_IT_TXE USART_IT_TC 使能串口外设 中断处理函数 背景 单片…

大语言模型多代理协作(MACNET)

大语言模型多代理协作(MACNET) Scaling Large-Language-Model-based Multi-Agent Collaboration 提出多智能体协作网络(MACNET),以探究多智能体协作中增加智能体数量是否存在类似神经缩放定律的规律。研究发现了小世界协作现象和协作缩放定律,为LLM系统资源预测和优化…

安川伺服控制器MP系列优势特点及行业应用

在工业自动化领域&#xff0c;运动控制器的性能直接决定了设备的精度、效率和可靠性。作为全球领先的运动控制品牌&#xff0c;安川电机伺服控制器凭借其卓越的技术优势和广泛的应用场景&#xff0c;正在为智能制造注入强劲动力&#xff01; MP3100&#xff1a;主板型运动控制…

AIoT时代来临,物联网技术如何颠覆未来生活?

在这个万物互联的时代&#xff0c;“物联网”&#xff08;IoT&#xff09;正以前所未有的速度改变我们的生活&#xff0c;而“AIoT”则是在物联网基础上融入人工智能技术&#xff0c;赋予设备更高的智能和自主决策能力。随着5G、边缘计算和云技术的不断发展&#xff0c;物联网正…

2025.2.11

1> 制作一个闹钟软件 .h #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QTime> #include <QTimer> #include <QTimeEdit> #include <QDa…

安装OpenJDK21(linux、macos)

文章目录 安装OpenJDK21java21linux下安装配置mac下安装 安装OpenJDK21 java21 封神&#xff01;Java 21正式发布了&#xff0c;迎来了史诗级新特性&#xff0c;堪称版本最强&#xff01;&#xff01;&#xff01; 视频链接&#xff1a;https://www.bilibili.com/video/BV1E8…

PortSwigger——WebSockets vulnerabilities

文章目录 一、WebSockets二、Lab: Manipulating WebSocket messages to exploit vulnerabilities三、Lab: Manipulating the WebSocket handshake to exploit vulnerabilities四、Using cross-site WebSockets to exploit vulnerabilities4.1 跨站WebSocket劫持&#xff08;cro…

SpringBootWeb三层架构分层解耦

SpringBootWeb 1. SpringBootWeb案例1.1 控制层未拆分代码1.2 实体类1.3 静态资源文件1.4 txt文件1.5 运行界面展示 2. 三层架构拆分2.1 控制层&#xff08;Controller&#xff09;2.1.1 功能2.1.2 用户信息控制层 2.2 业务逻辑层&#xff08;Service&#xff09;2.2.2 功能2.2…

Kimi k1.5: Scaling Reinforcement Learning with LLMs

TL;DR 2025 年 kimi 发表的 k1.5 模型技术报告&#xff0c;和 DeepSeek R1 同一天发布&#xff0c;虽然精度上和 R1 有微小差距&#xff0c;但是文章提出的 RL 路线也有很强的参考意义 Paper name Kimi k1.5: Scaling Reinforcement Learning with LLMs Paper Reading Note…