• react redux 状态管理


    1.store

    store是一个状态管理容器,它通过createStore创建,createStore接收initialState和reducer两个参数。它暴露了4个api分别是:

    getState()
    dispatch(action)
    subscribe(listener)
    replaceReducer

    前三个是比较常用的api,之后我们会来模拟实现一个createStore这个函数。

    2.action

    redux思想中view的变化由action发出通知,action是一个包含type的简单对象,在redux思想中改变state的唯一方法就是触发action

    3.dispatch

    dispatch用来处理action,并传递给reducer,继而更新应用状态

    4.reducer

    Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
    Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
    在React中使用redux的数据流向如图所示:

    在这里插入图片描述

    结构如下

    在这里插入图片描述
    store.js

    import { createStore } from 'redux'
    import { rootReducer } from './reducer/index';
    
    const store = createStore(rootReducer)
    
    export default store;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    action/index.js

    /**
     * action 构建函数
     */
    export const sendAction = (obj) => {
      // console.log(obj);
      // 需要返回一个action对象,该action对象需要包括type等属性
      return {
        type: 'send-action',
        value: '这是一个action'
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    redecer/index.js

    /**
     * 该文件是创建reducer函数,专门用于处理发送过来的action
     */
    
    const initState = {
      value: '默认值'
    }
    // 函数需要传递两个参数:state,action
    const rootReducer = (state = initState, action) => {
      // 根据aciton中的type字段判断是否为发送过来的action,如果是则返回一个新的state
      switch (action.type) {
        case 'send-action':
          return Object.assign({}, state, action)
        default:
          return state
      }
    }
    export {
      rootReducer
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    项目中使用
    …未完待续

  • 相关阅读:
    使用Java调用Yolo模型的准备工作与输入输出
    【苹果家庭推送iMessage】软件安装UITableViewController
    excel查找与引用函数
    重磅!涵盖全微服务操作的Spring Cloud 文档竟出自Alibaba
    17_Vue列表过滤_js模糊查询
    【前端】css控制页面提高亮度
    c++ 查看数据存放的内存段
    Android APT
    13.3 正则表达式的应用
    比较各JAX-RS实现:Jersey,Restlet,CXF,RESTEasy
  • 原文地址:https://blog.csdn.net/super__code/article/details/113899692