zoukankan      html  css  js  c++  java
  • Redux源码分析之基本概念

    Redux源码分析之基本概念

    Redux源码分析之createStore

    Redux源码分析之bindActionCreators

    Redux源码分析之combineReducers 

    Redux源码分析之compose 

     Redux源码分析之applyMiddleware 

    redux版本 3.7.2 (注: 分析的是redux,不是react-redux, 我这里是直接引入浏览器里,所以出现的 self.Redux,不要惊奇

    借用一张图,先了解下redux的几个概念

    action: 一个操作的定义,大概是这个样子, 本身是一个对象

    {
        type:'add',
        todo  
    }
    

    actionCreater: 一个函数,返回结果是一个action

    function add (todo) {
            return {
                type: 'add',
                todo
            }
        }
    

    reducer: 真正更新数据操作的函数,大概是这么个样子

    // reducer
    let todoReducer = function (state = todoList, action) {
        switch (action.type) {
            case 'add':
                return [...state, action.todo]
            case 'delete':
                return state.filter(todo => todo.id !== action.id)
            default:
                return state
        }
    }
    

    store: 只有一个。把action,state,reducer连接起来的对象。有如下方法

    • dispatch:触发一个action
    • subscribe : 订阅store
    • getState :获得当前的state
    • replaceReducer :更换reducer
    • observable :暂无研究(尴尬)

    我们先来一个简单的示例,直接dispatch action模式。这里大家应该都懂,不然。。。。。。

    /* 简单示例 */
    let { createStore } = self.Redux
    
    //默认state
    let todoList = []
    // reducer
    let todoReducer = function (state = todoList, action) {
        switch (action.type) {
            case 'add':
                return [...state, action.todo]
            case 'delete':
                return state.filter(todo => todo.id !== action.id)
            default:
                return state
        }
    }
    
    //创建store
    let store = createStore(todoReducer)
    
    //订阅
    function subscribe1Fn() {
        console.log(store.getState())
    }
    let sub = store.subscribe(subscribe1Fn)
    
    store.dispatch({
        type: 'add',
        todo: {
            id: 1,
            content: '学习redux'
        }
    })
    
    store.dispatch({
        type: 'add',
        todo: {
            id: 2,
            content: '吃饭睡觉'
        }
    })
    
    store.dispatch({
        type: 'delete',
        id: 2
    })
    
    // 取消订阅
    sub()
    
    console.log('取消订阅后:')
    store.dispatch({
        type: 'add',
        todo: {
            id: 3,
            content: '打游戏'
        }
    })  

     输出如下:

    createStore传入reducer生成store,store就可以订阅,和派发事件了,还是比较简单的。

    • subscribe 是可以取消的,subscribe返回的是一个函数,执行该函数就会取消订阅。 

    下一篇,我们来一起分析 createStore方法。

  • 相关阅读:
    【664】日常记录
    【663】dataframe 删掉指定行或者列
    【662】TensorFlow GPU 相关配置
    【661】Python split 指定多个分隔符
    【660】TensorFlow 或者 keras 版本问题
    FFMPEG视音频编解码
    cpplint中filter参数
    升级pip之后出现sys.stderr.write(f“ERROR: {exc}“)
    特征点三角化恢复3D点
    VIO——陀螺仪零偏估计
  • 原文地址:https://www.cnblogs.com/cloud-/p/7277056.html
Copyright © 2011-2022 走看看