目录
redux原理
redux中创建Store 的方式是createStore(),那么createStore()又是什么原理实现的呢?
createStore()
先来看看store是怎么创建的
import { createStore, combineReducers, applyMiddleware } from 'redux'
import counter from '../reducer/counter'
import thunk from 'redux-thunk'
import logger from 'redux-logger'
// 创建reducer 具体状态执行者
const store = createStore(
combineReducers({ counter }),
applyMiddleware(logger, thunk)
)
export default store
可以看到,createStore()接收了两个参数一个是combineReducers(),第二个是功能性插件合并applyMiddleware。
import {createStore,combineReducers,
applyMiddleware} from redux
store.getState()
this.unsubscribe = store.subscribe()
this.unsubscribe()
createStore
是一个函数,接收三个参数reducer,preloadedState,
enhancer。
enhancer
是一个高阶函数,用于增强create出来的store,他的参数是createStore
,返回一个更强大的store生成函数。(功能类似于middleware)。- 我们mobile仓库中的
storeCreator
其实就可以看成是一个enhancer,在createStore的时候将saga揉入了进去只不过不是作为createStore的第三个参数完成,而是使用middleware
完成。
export default function createStore(reducer,preloadedState,enchancer) {
if (typeof preloadedState === 'function' && typeof enhancer === 'function'
|| typeof enhancer === 'function' && typeof arguments[3] === 'function') {
throw new Error('It looks like you are passing several store enhancers to ' +
'createStore(). This is not supported. Instead, compose them ' + 'together to a
single function.');
}
//如果传递了第二个参数preloadedState,而且第二个参数不是一个function , 则将preloadedState 保存在内部变量currentState中, 也就是我们给State 的默认状态
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState;
preloadedState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.');
}
// createStore 作为enhancer的参数,返回一个被加强的createStore,然后再将reducer, preloadedState传进去生成store
return enhancer(createStore)(reducer, preloadedState);
}
//第一个参数reducer 是必须要传递的而且必须是一个函数,不然Redux会报错
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
//仓库内部保存了一颗状态树。可以是任意类型
let currentState = preloadedState;
let currentListeners=[];
let currentReducer = reducer
function getState() {
return JSON.parse(JSON.stringify(state));
}
//组件可以派发动作给仓库
function dispatch(action) {
//调用reducer进行处理,获取老的state,计算出新的state
currentState=currentReducer(currentState,action);
//通知其他的组件执行
currentListeners.forEach(l=>l());
}
//如果说其他的组件需要订阅状态变化时间的话,
function subscribe(listener) {
//将监听函数放入一个队列中
currentListeners.push(listener);
return function () {
currentListeners = currentListeners.filter(item=>item!==listener);
}
}
//初始化的操作
dispatch({type:'@@INIT'});
return {
getState,
dispatch,
subscribe
}
}
ComBineReducers()
为什么要⽤
combineReducers
呢
:
因为这样可