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>

    )

}

使用效果

相关推荐
ConardLi18 分钟前
开源我的 GPT-Image2 生图 Skill,附大量玩法指南
前端·人工智能·后端
我是Superman丶23 分钟前
Antigravity Retry 自动重试脚本
前端·javascript·vue.js
是大强32 分钟前
nvm安装node成功npm失败
前端·npm·node.js
im_AMBER41 分钟前
Leetcode 162 除了自身以外数组的乘积 | 接雨水
开发语言·javascript·数据结构·算法·leetcode
\xin1 小时前
pikachu自编CSRF(GET),CSRF(POST),CSRF(token)
前端·csrf
是大强1 小时前
前端一个项目用node20 一个项目用node14 怎么切换
前端
不老刘1 小时前
Git Cherry-Pick:微前端架构下的“精准医疗”与最佳实践
前端·git
Komorebi_99991 小时前
前端开发|18 个高频易错知识点汇总(HTML+CSS+JS+Vue)面试 & 开发通用
javascript·css·html
LIO1 小时前
ESLint 极简指南:让代码既规范又一致
前端·eslint
明月_清风2 小时前
前端工程化七连问:从紧急修复到版本控制,一文打通工程化任督二脉
前端·前端工程化