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>

    )

}

使用效果

相关推荐
IT_陈寒31 分钟前
Python开发者必须掌握的12个高效数据处理技巧,用过都说香!
前端·人工智能·后端
gnip8 小时前
企业级配置式表单组件封装
前端·javascript·vue.js
一只叫煤球的猫9 小时前
写代码很6,面试秒变菜鸟?不卖课,面试官视角走心探讨
前端·后端·面试
excel10 小时前
Three.js 材质(Material)详解 —— 区别、原理、场景与示例
前端
掘金安东尼10 小时前
抛弃自定义模态框:原生Dialog的实力
前端·javascript·github
hj5914_前端新手14 小时前
javascript基础- 函数中 this 指向、call、apply、bind
前端·javascript
薛定谔的算法14 小时前
低代码编辑器项目设计与实现:以JSON为核心的数据驱动架构
前端·react.js·前端框架
Hilaku14 小时前
都2025年了,我们还有必要为了兼容性,去写那么多polyfill吗?
前端·javascript·css
yangcode14 小时前
iOS 苹果内购 Storekit 2
前端
LuckySusu14 小时前
【js篇】JavaScript 原型修改 vs 重写:深入理解 constructor的指向问题
前端·javascript