当前位置: 首页 > news >正文

Redux在React中的使用

Redux在React中的使用

1.构建方式

采用reduxjs/toolkit+react-redux的方式
安装方式

npm install @reduxjs/toolkit react-redux

2.使用

①创建目录

在这里插入图片描述
创建store文件夹,然后创建index和对应的模块,如上图所示

②编写counterStore.js

文章以counterStore命名,名字可自行取

import {createSlice} from '@reduxjs/toolkit'
const counterStore=createSlice({name:'counter',//初始化状态数据initialState:{count:0},reducers:{increment(state){state.count++},decrement(state){state.count--}}
})
//解构出创建action对象的函数
const {increment,decrement}=counterStore.actions
//获取reducer函数
const counterReducer=counterStore.reducer
export {increment,decrement}
export default counterReducer

③编写index.js

import {configureStore} from "@reduxjs/toolkit"
import counterReducer from "./modules/counterStore";//创建根store组合子模块
const store=configureStore({reducer:{counter:counterReducer}
})
export default store

④在根组件中导入
使用react-redux中Provider进行导入

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from "./store";
import {Provider} from "react-redux";const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Provider store={store}><App /></Provider>
);

⑤在组件中使用
使用useSelector获取store中的数据

const ComponentDemo=()=>{const {count}=useSelector(state => state.counter)return(<div>{count}</div>)
}export default ComponentDemo

使用useDispatch获取dispatch方法,提交对应的方法改变state的值

const GrandSon=()=>{const dispatch=useDispatch()return(<div onClick={()=>{dispatch(decrement())}}>我是孙子组件</div>)
}
http://www.lryc.cn/news/245759.html

相关文章:

  • Go 数字类型
  • 时间序列预测 — Informer实现多变量负荷预测(PyTorch)
  • 2023年金融信创行业研究报告
  • 51单片机按键控制LED灯亮灭的N个玩法
  • 推荐6款本周 yyds 的开源项目
  • 【Git】git 更换远程仓库地址三种方法总结分享
  • springboot 返回problem+json
  • AI动画制作 StableDiffusion
  • 【开源】基于Vue和SpringBoot的木马文件检测系统
  • 5 动态规划解分割等和子串
  • file_get_contents() 函数详解与使用
  • 某医生用 ChatGPT 在 4 个月内狂写 16 篇论文,其中 5 篇已发表,揭密ChatGPT进行论文润色与改写的秘籍
  • 进程等待讲解
  • MySQL Binlog深度解析:进阶应用与实战技巧【进阶应用】
  • openpnp - 给底部相机加防尘罩
  • mac mysql连接中断重新启动办法
  • 【Vue3】解决Vue打包后上传服务器 资源路径加载错误
  • u-popup组件在UniApp中的讲解
  • drool 7 multiThread 测试
  • 【网安AIGC专题】46篇前沿代码大模型论文、24篇论文阅读笔记汇总
  • 如何在Simulink中使用syms?换个思路解决报错:Function ‘syms‘ not supported for code generation.
  • 论文导读 | 10月专题内容精选:人的预测
  • 深度学习18
  • Mysql数据库 18.Mysql SQL优化
  • [AutoSAR 存储] 汽车智能座舱的存储需求
  • 大数据-之LibrA数据库系统告警处理(ALM-37006 Coordinator进程异常)
  • python 列表的操作
  • Vue快速实践总结 · 上篇
  • 外汇天眼:香港监管机构对AMTD Global Markets Limited启动法律诉讼
  • OpenCV入门教程