createStore
返回一个对象:
- dispatch:分发一个action
- getState:得到仓库中当前的状态
- subscribe:注册一个监听器,监听器是一个无参函数,该分发一个action之后,会运行注册的监听器。该函数会返回一个函数,用于取消监听
/**
*
* @param {*} obj 对象
* @returns 判断是否是平面对象
*/
function isPlainObject(obj) {
if (typeof obj !== 'object') {
return false;
}
return Object.getPrototypeOf(obj) === Object.prototype;
}
/**
*
* @param {*} length
*/
function RandomStr(length) {
return Math.random().toString(36).substr(2, length).split('').join('.')
}
/**
*
* @param {*} reducer
* @param {*} defaultState
* @returns
*/
export default function (reducer, defaultState) {
let currState = defaultState,
currReducer = reducer;
const listeners = [];
function dispatch(action) {
// 判断action是平面对象
if (!isPlainObject(action)) {
throw TypeError('action must be a plain objet')
}
if (action.type === undefined) {
throw TypeError('action must be have property of type')
}
currState = currReducer(currState, action);
for (const listener of listeners) {
listener();
}
}
function getState() {
return currState;
}
function subscribe(listener) {
listeners.push(listener);
let isRemove = false;
return function () {
if (isRemove) {
return;
}
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
isRemove = true;
console.log('listeners', listeners)
}
}
dispatch({
type: `@@redux/INIT${RandomStr()}`
})
return {
dispatch,
getState,
subscribe
}
}