资讯专栏INFORMATION COLUMN

状态管理从0开始[后续更新]

OnlyLing / 409人阅读

摘要:命名一个要一个只读创建一些列改变需要一个监听改变每一次改变状态的时候执行调用返回状态优化想要第一次监听的时候返回当前状态监听改变状态统一使用调用法打印日志信息监听改变之前的状态监听改变之后的状态可以少写好多个优化想要第一次监听的时候返回当前

Step01.命名一个storeService要一个只读state
var storeService = new Object({
    _state: { age: 1 },
    get state() {
        return this._state;
    },
    set state(v) {
        throw new Error(" is read only.")
    }
});
Step02.创建一些列mutation改变state
var storeService = new Object({
    _state: { age: 1 },
    get state() {
        return this._state;
    },
    set state(v) {
        throw new Error(" is read only.")
    },
    mutationModifyAge(newAge) {
        state.age = newAge;
    },
    mutationModifyAge2(newAge) {
        state.age = newAge;
    },
    mutationModifyAge3(newAge) {
        state.age = newAge;
    }
});
Step03.需要一个watch监听改变,每一次改变状态的时候(执行mutation)调用listenCallback 返回状态
var storeService = new Object({
    _listeners: [],
    _state: { age: 1 },
    get state() {
        return this._state;
    },
    set state(v) {
        throw new Error(" is read only.")
    },
    mutationModifyAge(newAge) {
        state.age = newAge;
        this._dealCallback();
    },
    mutationModifyAge2(newAge) {
        state.age = newAge;
        this._dealCallback();
    },
    mutationModifyAge3(newAge) {
        state.age = newAge;
        this._dealCallback();
    },
    _dealCallback() {
        this._listeners.forEach(listener => listener(this.state))

    },
    watch(listener) {
        // 优化想要第一次监听的时候返回当前状态
        listener(this.state);
        this._listeners.push(listener);
    }
});
// 监听store
storeService.watch(function (state) {
    console.log("callback", state);
})
// 改变状态
storeService.mutationModifyAge(2)
Step04.统一使用dispatch调用mutation法
var storeService = new Object({
    _listeners: [],
    _state: { age: 1 },
    get state() {
        return this._state;
    },
    set state(v) {
        throw new Error(" is read only.")
    },
    dispatch(type, ...paylod) {
        // 打印日志信息
        console.log(type ? type : "监听", "改变之前的状态", this.state);
        if (this._mutation[type]) {
            this._mutation[type](this.state, ...paylod);
        }
        console.log(type ? type : "监听", "改变之后的状态", this.state);
        // 可以少写好多个listenCallback
        this._dealCallback();
    },
    _mutation: {
        mutationModifyAge(state, newAge) {
            state.age = newAge;
        },
        mutationModifyAge2(state, newAge) {
            state.age = newAge;
        },
        mutationModifyAge3(state, newAge) {
            state.age = newAge;
        }
    },
    _dealCallback() {
        this._listeners.forEach(listener => listener(this.state))

    },
    watch(listener) {
        // 优化想要第一次监听的时候返回当前状态
        // listener(this.state);
        // 优化让第一次监听也可以记录历史日志
        this.dispatch();
        this._listeners.push(listener);
    }
});
// 监听store
storeService.watch(function (state) {
    console.log("callback", state);
})
// 改变状态
storeService.dispatch("mutationModifyAge", 2)
以上内容为创建一个简单的store。
以下开始按照Vuex0.3.0开始优化
Step05.vuex dispatcher调用的方法是mutation,
mutation是唯一操作state的方法,
mutation不可包含任何副作用,
mutation对外暴露dispatch调用将上面的mutation 改为mutation
var storeService = new Object({
    _listeners: [],
    _state: { age: 1 },
    get state() {
        return this._state;
    },
    set state(v) {
        throw new Error(" is read only.")
    },
    dispatch(type, ...paylod) {
        // 打印日志信息
        console.log(type ? type : "监听", "改变之前的状态", this.state);
        if (this._mutation[type]) {
            this._mutation[type](this.state, ...paylod);
        }
        console.log(type ? type : "监听", "改变之后的状态", this.state);
        // 可以少写好多个listenCallback
        this._dealCallback();
    },
    _mutation: {
        mutationModifyAge(state, newAge) {
            state.age = newAge;
        },
        mutationModifyAge2(state, newAge) {
            state.age = newAge;
        },
        mutationModifyAge3(state, newAge) {
            state.age = newAge;
        }
    },
    _dealCallback() {
        this._listeners.forEach(listener => listener(this.state))

    },
    watch(listener) {
        // 优化想要第一次监听的时候返回当前状态
        // listener(this.state);
        // 优化让第一次监听也可以记录历史日志
        this.dispatch();
        this._listeners.push(listener);
    }
});
// 监听store
storeService.watch(function (state) {
    console.log("callback", state);
})
// 改变状态
storeService.dispatch("mutationModifyAge", 2)
Step05.vuex中mutation为纯函数,不可包含任何副作用,添加action来处理一系列副作用,最终还是调用dispatch 去改变state
var storeService = new Object({
    _listeners: [],
    _state: { age: 1 },
    get state() {
        return this._state;
    },
    set state(v) {
        throw new Error(" is read only.")
    },

    dispatch(type, ...paylod) {
        // 打印日志信息
        console.log(type ? type : "监听", "改变之前的状态", this.state);
        if (this._mutation[type]) {
            this._mutation[type](this.state, ...paylod);
        }
        console.log(type ? type : "监听", "改变之后的状态", this.state);
        // 可以少写好多个listenCallback
        this._dealCallback();
    },
    _mutation: {
        mutationModifyAge(state, newAge) {
            state.age = newAge;
        },
        mutationModifyAge2(state, newAge) {
            state.age = newAge;
        },
        mutationModifyAge3(state, newAge) {
            state.age = newAge;
        }
    },
    _dealCallback() {
        this._listeners.forEach(listener => listener(this.state))
    },
    watch(listener) {
        // 优化想要第一次监听的时候返回当前状态
        // listener(this.state);
        // 优化让第一次监听也可以记录历史日志
        this.dispatch();
        this._listeners.push(listener);
    },
    bindAction(actions) {
        this.actions = Object.create(null);
        this._actions = Object.create(null);

        function createAction(action, store) {
            if (typeof action === "function") {
                return (...payload) => action(store, ...payload)
            }
        }
        Object.keys(actions).forEach(name => {
            console.log(actions[name]);
            this._actions[name] = createAction(actions[name], this)
            if (!this.actions[name]) {
                this.actions[name] = (...args) => this._actions[name](...args)
            }
        })
    }
});
var actions = {
    // 包含副作用的action
    asyncModifyAge(store, ...paylod) {
        setTimeout(() => {
            store.dispatch("mutationModifyAge", ...paylod)
        }, 2000);
    },
    // 多次调用dispatch
    asyncMulModifyAge(store, ...paylod) {
        setTimeout(() => {
            store.dispatch("mutationModifyAge", ...paylod)
        }, 2000);
        store.dispatch("mutationModifyAge2", ...paylod)
    }
}
storeService.bindAction(actions);
// 监听store
storeService.watch(function (state) {
    console.log("callback", state);
})
// 改变状态
storeService.dispatch("mutationModifyAge", 2)
storeService.actions.asyncMulModifyAge(21);
Step06 封装成一个类hKeeper
var defaultOption = {
    state: {},
    actions: {},
    mutations: {}
};
class hKeeper {
    constructor(options) {
        options = Object.assign({}, defaultOption, options);
        this._state =  options.state;
        this.listeners = [];
        const dispatch = this.dispatch;
        this.dispatch = (...args) => {
            dispatch.apply(this, args);
        };
        this.actions = Object.create(null);
        this._setupMutations(options.mutations);
        this._setupActions(options.actions);
    }
    get state() {
        return this._state
    }

    set state(v) {
        throw new Error("[hKeeper] hKeeper state is read only.")
    }
    dispatch(type, ...payload) {
        const mutation = this._mutations[type]
        const state = this.state
        if (mutation) {
            mutation(state, ...payload)
        }
        this.listeners.forEach(listener => listener(this.state))
    }
    _setupMutations(mutations) {
        this._mutations = mutations;
    }
    // 设置action
    _setupActions(actions) {
        function createAction(action, store) {
            if (typeof action === "function") {
                return (...payload) => action(store, ...payload)
            }
        }
        this._actions = Object.create(null)
        Object.keys(actions).forEach(name => {
            this._actions[name] = createAction(actions[name], this)
            if (!this.actions[name]) {
                this.actions[name] = (...args) => this._actions[name](...args)
            }
        })
    }
    watch(listener) {
        listener(this.state);
        this.listeners.push(listener)
    }
}
var storeService = new hKeeper(
    {
        state: { age: 1 },
        actions: {
            // 包含副作用的action
            asyncModifyAge(store, ...paylod) {
                setTimeout(() => {
                    store.dispatch("mutationModifyAge", ...paylod)
                }, 2000);
            },
            // 多次调用dispatch
            asyncMulModifyAge(store, ...paylod) {
                setTimeout(() => {
                    store.dispatch("mutationModifyAge", ...paylod)
                }, 2000);
                store.dispatch("mutationModifyAge2", ...paylod)
            }
        },
        mutations: {
            mutationModifyAge(state, newAge) {
                state.age = newAge;
            },
            mutationModifyAge2(state, newAge) {
                state.age = newAge;
            },
            mutationModifyAge3(state, newAge) {
                state.age = newAge;
            }
        }
    }
)
// 监听store
storeService.watch(function (state) {
    console.log("callback", state);
})
// 改变状态
storeService.dispatch("mutationModifyAge", 2)
storeService.actions.asyncMulModifyAge(21);
参考Vuex0.3.0版本 applyMiddleware 参考Redux 
https://github.com/HereSincer...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/90674.html

相关文章

  • 不可不说的Java“锁”事

    摘要:本文旨在对锁相关源码本文中的源码来自使用场景进行举例,为读者介绍主流锁的知识点,以及不同的锁的适用场景。中,关键字和的实现类都是悲观锁。自适应意味着自旋的时间次数不再固定,而是由前一次在同一个锁上的自旋时间及锁的拥有者的状态来决定。 前言 Java提供了种类丰富的锁,每种锁因其特性的不同,在适当的场景下能够展现出非常高的效率。本文旨在对锁相关源码(本文中的源码来自JDK 8)、使用场景...

    galaxy_robot 评论0 收藏0
  • JStorm源码分析系列--01--Nimbus启动分析

    摘要:方法首先初始化一个回调函数,这是当一个成为之后就会调用的一个用于初始化一系列变量的方法,包括拓扑如何在集群上分配,拓扑状态更新,清除函数,还有监控线程等。 写在前面的话,笔者第一次阅读框架源码,所以可能有些地方理解错误或者没有详细解释,如果在阅读过程发现错误很欢迎在文章下面评论指出。文章后续会陆续更新,可以关注或者收藏,转发请先私信我,谢谢。对了,笔者看的是2.2.1这个版本 概述  ...

    Carbs 评论0 收藏0
  • React Hook起飞指南

    摘要:起飞指南作者元潇方凳雅集出品目前放出来了个内置,但仅仅基于以下两个,就能做很多事情。行代码实现一个全局元潇根组件挂上即可子组件调用随时随地实现一个局部元潇的本质是的一个语法糖,感兴趣可以阅读一下的类型定义和实现。 React Hook起飞指南 作者:元潇 方凳雅集出品 16.8目前放出来了10个内置hook,但仅仅基于以下两个API,就能做很多事情。所以这篇文章不会讲很多API,...

    姘搁『 评论0 收藏0
  • 聊一聊H5应用缓存-Manifest

    摘要:原文聊一聊应用缓存导读是提供的一种应用缓存机制基于它应用可以实现离线访问为此浏览器还提供了应用缓存的虽然的技术已被标准废弃但这不影响我们尝试去了解它也正是因为的应用缓存机制如此诱人饿了么和邮箱等都还在使用着它描述对熟悉的同学可以跳过此 原文: 聊一聊H5应用缓存-Manifest 导读 Manifest 是 H5提供的一种应用缓存机制, 基于它web应用可以实现离线访问(offline...

    陈伟 评论0 收藏0
  • 我的Android重构之旅:架构篇

    摘要:是的架构的实现。是在年提出的一种前端架构,主要用来处理复杂的逻辑的一致性问题当时是为了解决页面的消息通知问题。 去年10月底来到了新公司,刚开始接手 Android 项目时,发现该项目真的是一团遭,项目开发上没有任何架构可言,开发人员连简单的 MVC、MVP 都不了解,Activity 及其臃肿,业务边界也不明确,因此我决定重新分析一下当前主流的几种开发架构,选出适合当前项目的架构形式...

    mylxsw 评论0 收藏0

发表评论

0条评论

OnlyLing

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<