2021-04-26

redux原理核心实现

createStore

创建 store 对象,包含 getState, dispatch, subscribe, replaceReducer

reducer

reducer 是一个计划函数,接收旧的 state 和 action,生成新的 state

action

action 是一个对象,必须包含 type 字段

dispatch

dispatch( action ) 触发 action,生成新的 state

subscribe

实现订阅功能,每次触发 dispatch 的时候,会执行订阅函数

combineReducers

多 reducer 合并成一个 reducer

replaceReducer

替换 reducer 函数

middleware

扩展 dispatch 函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        function createStore(reducers){
            //定义一个状态
            let state = null;

            //定义一个数组,存放一组在状态发生变换的时候处理的业务
            let listeners = []
            //发布订阅模式
            function subscirbe(fn){
                listeners.push(fn)
            }
            function dispatch(action) {
                //reducer来源于reduce,一定是一个纯函数
                state = reducers(state,action)
                //出发listener里的函数
                listeners.forEach(fn =>fn())
            }

            function getState(){
                return state
            }
            //目的是初始化一次初始状态
            dispatch({
                type: "afasdf"
            })
            return {
                dispatch,
                getState,
                subscirbe
            }

        }

        const defaultState = {
            count: 0
        }

        function reducers(state,action){
            //初始化state
            if(!state){
                state = defaultState
            }
            switch(action.type){
                case 'add':
                    //返回一个新的state
                    return {
                        count: state.count + 1
                    }
                case 'minus':
                    return {
                        count: state.count - 1
                    }
                default:
                    return state
            }
        }

        const store =  createStore(reducers)
        
        store.subscirbe(()=>{
            console.log(store.getState())
        })
        store.dispatch({type:'add'})
        store.dispatch({type:'add'})
        store.dispatch({type:'add'})
    </script>
</body>
</html>
//{count: 1}
//{count: 2}
//{count: 3}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值