Redux 小demo

在这里插入图片描述reducer(state,action):当前的state和action,返回新的state;
store:存放state的对象;
state:唯一的state值,通过store.getState()获取;
Action:普通对象,用来表示即将改变state。action 内必须使用一个字符串类型的 type 字段来表示将要执行的动作;
Dispatch(action):往store发送action;
Action Create:创建action的函数

      const createStore = (reducer) =>{  //返回dispath、getstate、subscribe
            let state;
            const list = [];
            const dispath = (action) => {//触发action
                state = reducer(state,action);
                list.forEach((cb)=>{
                    cb()
                });
            }

            const getState = () => {//获取state
                return state
            }
            const subscribe = (callback) => {//订阅回调函数
                list.push(callback)
            }

            return {
                dispath,
                getState,
                subscribe

            }
        }
        const reducer = (state,action)=>{
            if (state === undefined) {
                return 0
            } 
            switch (action.type) {
                case 'DECREASEMENT':
                    return state+1
                    break;
                case 'INCREASEMENT':
                    return state-1
                    break;
            }
        }
        const store = createStore(reducer)

        store.subscribe(()=>{
            console.log('fn1-----:'+store.getState())
        })
        store.subscribe(()=>{
            console.log('fn2-----:'+store.getState())
        })

        store.dispath({
            type:'DECREASEMENT'
        })
        store.dispath({
            type:'INCREASEMENT'
        })
        store.dispath({
            type:'INCREASEMENT'
        })
发布了38 篇原创文章 · 获赞 1 · 访问量 550

猜你喜欢

转载自blog.csdn.net/weixin_43718291/article/details/103501269