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

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--
        },
        setCountData(state,action){
            state.count=action.payload
        }
    }
})
//解构出创建action对象的函数
const {increment,decrement,setCountData}=counterStore.actions
//获取reducer函数
const counterReducer=counterStore.reducer
export {increment,decrement,setCountData}
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.kler.cn/a/152504.html

相关文章:

  • Kafka的存储机制和可靠性
  • 在线html地址转html文本
  • 马斯克对openAI动荡的看法:Ilya道德感强,他认真了一定是严肃问题
  • Nacos 架构原理
  • KAO2 入门到熟练 看这一篇文章就够了
  • MySQL的安装步骤教程以及基本操作--详细讲解
  • ChatGPT 问世一周年之际,开源大模型能否迎头赶上?
  • 口碑最好超声波清洗机有哪些?2023年超声波清洗机排行榜
  • 数据库安全运维系统厂家在深圳的有哪些?咨询电话多少?
  • java基础面试题(二)
  • Laravel修改默认的auth模块为md5(password+salt)验证
  • 电源控制系统架构(PCSA)之系统控制处理器组件
  • 企业软件手机app定制开发趋势|小程序网站搭建
  • Maven的安装和使用
  • opencv读取二进制灰度图并显示
  • 15 网关实战: 微服务集成Swagger实现在线文档
  • RPC与HTTP的详细比较
  • maven 基础
  • 大屏适配方案(vw、vh)
  • 抑制过拟合——从梯度的角度看LayerNorm的作用