关于前端:miniredux-实现原理讲解-第一讲

5次阅读

共计 1791 个字符,预计需要花费 5 分钟才能阅读完成。

文章首发于我的博客 https://github.com/mcuking/bl…

相干代码请查阅 https://github.com/mcuking/bl…

首先咱们不思考 react-redux,先思考如何实现 redux 的性能。
redux 依据 reducer(依据旧全局 state 和 action 生成新的全局 state)生成全局状态树 store。即

store = createStore(reducer)

上面咱们就首先实现 createStore 机制,代码如下,其中:

  • currentState 用来存储以后利用的全局状态
  • currentListeners 数组用来存储以后的所有监听函数,每当 store 有变动,store 就会调用传入 subscribe 的监听函数

同时生成的 store 具备如下 API:

  • getState 用来返回以后的 state
  • subscribe 用来订阅监听,行将所有监听函数 push 到 currentListeners
  • dipatch 用来派发 action,使得 reducer 能够依据 action 和旧的 state 生成新的 state,同时执行传入 currentListeners 的所有的监听函数

当第一次渲染时,须要生成一个初始化的 store,因而须要派发一个不存在的 action,action 的 type 命名尽量非凡,不与使用者的抵触,命名为 @@redux/INIT1

export function createStore(reducer) {let currentState = {}
    let currentListeners = []

    function getState() {return currentState}

    // 传入监听函数
    function subscribe(listener) {currentListeners.push(listener)
    }

    function dispatch(action) {
        // reducer 依据老的 state 和 action 计算新的 state
        currentState = reducer(currentState, action)
        // 当全局状态变动时,执行传入的监听函数
        currentListeners.forEach(v => v())
        return action
    }

    dispatch({type: '@@redux/INIT1'}) // 初始化全局状态
    return {getState, subscribe, dispatch}
}

这样咱们最简版本的 redux 就曾经实现了,上面是应用该最简版 redux 的利用代码

import React from 'react'
import ReactDOM from 'react-dom'
import {createStore} from './mini-redux'
import App from './App'

// 通过 reducer 建设 store(reducer 会依据老的 state 和 action,生成新的 state)function counter(state=0, action) {switch(action.type) {
        case '买一套房':
            return state + 1
        case '卖一套房':
            return state - 1
        default:
            return 10
    }
}

const store = createStore(counter)
// console.log(store, 'store')
const init = store.getState()


function listener() {const current = store.getState()
    // console.log(` 现有房子 ${current} 套 `)
}

// 监听,store 有变动,store 就会调用传入 subscribe 的函数
store.subscribe(listener)

// 派发事件,传递 action
store.dispatch({type: '买一套房'})
store.dispatch({type: '卖一套房'})
store.dispatch({type: '买一套房'})

接下来咱们将在此基础上,实现 react-redux 性能,以便在 react 中更优雅的应用 redux 进行全局状态治理。

相干文章如下:

  • mini-redux 实现原理解说 第一讲
  • mini-redux 实现原理解说 第二讲
  • mini-redux 实现原理解说 第三讲
  • mini-redux 实现原理解说 第四讲
正文完
 0