文章首发于个人博客 https://github.com/mcuking/bl...相关代码请查阅 https://github.com/mcuking/bl...react
首先咱们不考虑react-redux,先思考如何实现redux的功能。
redux根据reducer(根据旧全局state和action生成新的全局state)生成全局状态树store。即git
store = createStore(reducer)
下面咱们就首先实现createStore机制,代码以下,其中:github
同时生成的store具备以下API:redux
当第一次渲染时,须要生成一个初始化的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的应用代码dom
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进行全局状态管理。函数
相关文章以下:spa