文章首发于我的博客 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)// 派发事件, 传递actionstore.dispatch({type: '买一套房'})store.dispatch({type: '卖一套房'})store.dispatch({type: '买一套房'})
接下来咱们将在此基础上,实现react-redux性能,以便在react中更优雅的应用redux进行全局状态治理。
相干文章如下:
- mini-redux 实现原理解说 第一讲
- mini-redux 实现原理解说 第二讲
- mini-redux 实现原理解说 第三讲
- mini-redux 实现原理解说 第四讲