• 使用 Redux 管理全局状态


    Redux 是个状态集中管理框架,状态可以跨组件共享,状态更新后,调用监听器。其实状态可以认为就是个全局对象,为什么要做一个框架来管理呢?如果我们自己使用一个全解字典来管理状态是不是也行?如果不做任何控制,维护很有挑战,随着项目的增大,状态就会失控,所有的逻辑都可以更新,一旦发现问题不知道是被哪个组件更新的。所以 Redux 有自己一套规则,包括 Dispatcher、Store、Action,更新的数据通过 store 的 dispatcher 进行发送,reducer 是实际更新逻辑处理的组件,reducer 可以理解为监听器,他只会处理关注的 Action。

    Reducer 需要遵循一下规则

    1. 基于state 和 action 参数来计算新的状态值。
    2. 不允许修改现有状态。必须进行不可变更新,通过复制现有状态并更改复制的值。
    3. 他们不得执行任何异步逻辑、计算随机值或引起其他“副作用”。

    官网抄来图,官网是动图,Redux 的概念比较简单,写起来有点儿绕,但是现有了 Toolkit,写了挺简单的。
    在这里插入图片描述
    看个例子, action type 是 name + reducers的 function,比如 increment,就是“counter/increment".

    import { createSlice } from '@reduxjs/toolkit'
    
    export const counterSlice = createSlice({
      name: 'counter',
      initialState: {
        value: 0
      },
      reducers: {
        increment: state => {
          state.value += 1
        },
        decrement: state => {
          state.value -= 1
        },
        incrementByAmount: (state, action) => {
          state.value += action.payload
        }
      }
    })
    
    export const { increment, decrement, incrementByAmount } = counterSlice.actions
    
    export default counterSlice.reducer
    
    export const selectCount = state => state.counter.value
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
  • 相关阅读:
    Flutter-自定义短信验证码
    【2023集创赛】加速科技杯作品:高光响应的二硫化铼光电探测器
    第四章 重载&访问修饰符&静态&常用类 ② 代码
    Java之多态数组
    FineBI 取日期的最大max、最小值min
    中文drupal教程(3)响应对象Response及Cookie设置
    按键中断小灯蜂鸣器风扇
    比Xshell好用的ssh工具——FinalShell
    SQL中的约束
    SpringMVC入门
  • 原文地址:https://blog.csdn.net/hawk2014bj/article/details/138197223