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>

    )

}

使用效果

相关推荐
怕浪猫1 小时前
FDE 如何正确解决现场项目工程性的问题
前端·后端·ai编程
西瓜太郎12341 小时前
外层模型卡片与分组详情成功率不一致,应该怎么排查?
前端·typescript·go·软件工程·react
GreenTea1 小时前
vLLM 与 SGLang KV Cache 底层实现机制深度调研报告
前端·后端·算法
几何心凉4 小时前
没有万能模型:我用 AiiOnly Token Plan,把多款大模型的长处拼进同一个项目
前端
kyriewen4 小时前
Claude Code 的额度今天缩水了17%——官方公告上写的是"永久提高25%"
前端·ai编程·claude
雪芽蓝域zzs5 小时前
vue解构平铺VS对象包裹
前端·javascript·vue.js
风骏时光牛马6 小时前
从零到实战,完整AI学习路线
前端
三十而立洋6 小时前
深入理解 Monorepo:子包安装依赖
前端·前端工程化
IT_陈寒6 小时前
Java Stream处理大集合,我的内存怎么就炸了
前端·人工智能·后端
Captaincc7 小时前
AI 用量桌面端-桌面宠物自定义指南
前端·人工智能