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>
    )
}
相关推荐
飞羽殇情5 小时前
基于React Native鸿蒙跨平台开发构建完整电商预售系统数据模型,完成参与预售、支付尾款、商品信息展示等
react native·react.js·华为·harmonyos
摘星编程5 小时前
React Native + OpenHarmony:ImageSVG图片渲染
javascript·react native·react.js
摘星编程5 小时前
OpenHarmony + RN:Text文本书写模式
javascript·react native·react.js
xixixin_6 小时前
【React】中 Body 类限定法:优雅覆盖挂载到 body 的组件样式
前端·javascript·react.js
摘星编程7 小时前
用React Native开发OpenHarmony应用:Image网络图片加载
javascript·react native·react.js
摘星编程7 小时前
OpenHarmony环境下React Native:ImageBase64图片显示
javascript·react native·react.js
摘星编程8 小时前
React Native鸿蒙:Image本地图片显示
javascript·react native·react.js
2501_9219308311 小时前
基础入门 React Native 鸿蒙跨平台开发:Video 全屏播放与画中画 鸿蒙实战
react native·react.js·harmonyos
2501_9219308311 小时前
基础入门 React Native 鸿蒙跨平台开发:react-native-switch 开关适配
react native·react.js·harmonyos
摘星编程11 小时前
在OpenHarmony上用React Native:ImageGIF动图播放
javascript·react native·react.js