React全局状态管理

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

快速使用

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

index.js

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

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

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. react之useContext全局状态管理

    2024-01-17 22:44:02       69 阅读
  2. React状态管理详解

    2024-01-17 22:44:02       56 阅读
  3. zustand状态管理工具(react

    2024-01-17 22:44:02       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-17 22:44:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-17 22:44:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-17 22:44:02       87 阅读
  4. Python语言-面向对象

    2024-01-17 22:44:02       96 阅读

热门阅读

  1. C++ this 指针

    2024-01-17 22:44:02       49 阅读
  2. c++ STL总结

    2024-01-17 22:44:02       43 阅读
  3. 媒体捕捉-iOS中的人脸识别

    2024-01-17 22:44:02       52 阅读
  4. 工智能基础知识总结--词嵌入之Word2Vec

    2024-01-17 22:44:02       51 阅读
  5. word2vec中的CBOW和Skip-gram

    2024-01-17 22:44:02       55 阅读
  6. 深度解析 ThreadLocal 的多重应用场景

    2024-01-17 22:44:02       57 阅读
  7. C++ 并发编程 | 锁

    2024-01-17 22:44:02       47 阅读