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>

    )

}

使用效果

相关推荐
亦世凡华、17 分钟前
Rollup入门与进阶:为现代Web应用构建超小的打包文件
前端·经验分享·rollup·配置项目·前端分享
Bl_a_ck43 分钟前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
为美好的生活献上中指1 小时前
java每日精进 5.11【WebSocket】
java·javascript·css·网络·sql·websocket·网络协议
augenstern4162 小时前
webpack重构优化
前端·webpack·重构
海拥✘2 小时前
CodeBuddy终极测评:中国版Cursor的开发革命(含安装指南+HTML游戏实战)
前端·游戏·html
寧笙(Lycode)2 小时前
React系列——HOC高阶组件的封装与使用
前端·react.js·前端框架
asqq82 小时前
CSS 中的 ::before 和 ::after 伪元素
前端·css
拖孩3 小时前
【Nova UI】十五、打造组件库之滚动条组件(上):滚动条组件的起步与进阶
前端·javascript·css·vue.js·ui组件库
苹果电脑的鑫鑫3 小时前
element中表格文字剧中可以使用的属性
javascript·vue.js·elementui
Hejjon3 小时前
Vue2 elementUI 二次封装命令式表单弹框组件
前端·vue.js