Redux在React中的使用

Redux在React中的使用

1.构建方式

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

安装方式

bash 复制代码
npm install @reduxjs/toolkit react-redux

2.使用

①创建目录

创建store文件夹,然后创建index和对应的模块,如上图所示

②编写counterStore.js

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

javascript 复制代码
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

javascript 复制代码
import {configureStore} from "@reduxjs/toolkit"
import counterReducer from "./modules/counterStore";

//创建根store组合子模块
const store=configureStore({
    reducer:{
        counter:counterReducer
    }
})
export default store

④在根组件中导入

使用react-redux中Provider进行导入

javascript 复制代码
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中的数据

javascript 复制代码
const ComponentDemo=()=>{
    const {count}=useSelector(state => state.counter)
    return(
        <div>
            {count}
        </div>
    )
}

export default ComponentDemo

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

javascript 复制代码
const GrandSon=()=>{
    const dispatch=useDispatch()
    return(
        <div onClick={()=>{dispatch(decrement())}}>
            我是孙子组件
        </div>
    )
}
相关推荐
ZoeLandia15 小时前
React6:组件通信
前端·react.js·typescript
ZoeLandia19 小时前
React03:useState 与不可变更新
前端·react.js·typescript·react
鬼手点金19 小时前
单轮对话:最简单的 API 调用
java·服务器·前端·javascript·react.js·servlet·tomcat
console.log('npc')1 天前
从0到1实现任务评价统计功能:React + TypeScript 实战指南(小白注释版)
前端·react.js·typescript
ZoeLandia1 天前
React04:事件处理与受控表单
开发语言·前端·react.js·typescript
ZoeLandia1 天前
React05:useEffect 与副作用
开发语言·前端·react.js·typescript
濮水大叔2 天前
函数式与对象式:前端架构的两种成本曲线
vue.js·react.js·函数式编程
用户298698530142 天前
React 前端 Word 转图片:页面与元素级导出的工程实践
前端·javascript·react.js
志尊宝2 天前
AI原生前端开发(016):端侧AI与React 19结合实战
人工智能·react.js·ai-native
时间的情敌3 天前
《回顾 2019 前端:React Hooks 问世,前端工程化爆发的一年》
前端·react.js·前端框架