React全局状态管理

redux是一个状态管理框架,它可以帮助我们清晰定义state和处理函数,提高可读性,并且redux中的状态是全局共享,规避组件间通过props传递状态等操作。

快速使用

在React应用的根节点,需要借助React的Context机制存放整个store信息。需要进行以下配置。

index.js

javascript 复制代码
import React from 'react'
import ReactDOM from 'react-dom'

import {Provider} from 'react-redux'
import {store} from './store'
import App from './app'

const rootElement = document.getElementById('root');

ReactDOM.render(
    <Provider store = {store}>
        <App/>
    </Provider>,
    
    rootElement
    
)

store文件需要配置下Redux,包括reducer和action以及state

store.js

javascript 复制代码
import {createStore} from 'redux'


const initialState = {value: 0}


// Reducer
function counterReducer(state = initialState, action){
    switch (action.type){
        case 'counter/incremented':
            return {value: state.value + 1};
        case 'counter/decremented':
            return {value: state.value - 1};
        default:
            return state
    }
}

// Action
export const incrementAction = {type:'counter/incremented'}
export const decrementAction = {type: 'counter/decremented'}

// Redux 定义
export const store = createStore(counterReducer)

在业务逻辑中,需要通过useSelector和useDispatch自定义hook获取state和dispatch

Counter.js

javascript 复制代码
import React from 'react'
import {useDispatch, useSelector} from 'react-redux'
import {decrementAction, incrementAction} from "./store";

export function Counter() {

    const count = useSelector(state => state.value)

    const dispatch = useDispatch()

    return (
        <div>
            <button onClick={() => dispatch(incrementAction)}>
                +
            </button>
            <span>{count}</span>
            <button onClick={() => dispatch(decrementAction)}>
                -
            </button>
        </div>

    )

}

使用效果

相关推荐
Mapmost5 分钟前
【高斯泼溅】如何将“歪头”的3DGS模型精准“钉”在地图上,杜绝后续误差?
前端
JellyDDD6 分钟前
h5上传大文件可能会导致手机浏览器卡死,重新刷新的问题
javascript·上传文件
废春啊37 分钟前
前端工程化
运维·服务器·前端
爱上妖精的尾巴39 分钟前
6-9 WPS JS宏Map、 set、get、delete、clear()映射的添加、修改、删除
前端·wps·js宏·jsa
爱分享的鱼鱼1 小时前
对比理解 Vue 响应式 API:data(), ref、reactive、computed 与 watch 详解
前端·vue.js
JS_GGbond1 小时前
【性能优化】给Vue应用“瘦身”:让你的网页快如闪电的烹饪秘籍
前端·vue.js
T___T1 小时前
一个定时器,理清 JavaScript 里的 this
前端·javascript·面试
代码小学僧1 小时前
从 Arco Table 迁移到 VTable:VTable使用经验分享
前端·react.js·开源
微笑的曙光1 小时前
Vue3 环境搭建 5 步走(零基础友好)
前端
不知名用户来了1 小时前
基于vue3 封装的antdv/element-Plus 快速生成增删改查页面
前端