Skip to content

Instantly share code, notes, and snippets.

@Yang03 Yang03/redux
Created Jul 7, 2017

Embed
What would you like to do?
const log = (store) => (next) => (action) => {
console.log('start')
next(action)
console.log('end')
}
function applayMiddleware (...middlewares) {
return (createStore) => (reducer, preloadedState,enhancer) => {
const store = new createStore(reducer, preloadedState, enhancer)
let dispatch = store.dispatch
let chain = []
const middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = chain.reduce((a,b) => ((...args )=> a(b(...args))))(store.dispatch)
return {
...store,
dispatch
}
}
}
function createThunkMiddleware(extraArgument) {
return ({dispatch, getState}) => (next) => (action) => {
if (typeof action == 'function') {
return action(dispatch, getState, extraArgument)
}
return next(action)
}
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware
function createStore(reducer, preloadedState, enhancer ) {
let currentReducer = reducer
let currentState = preloadedState
let currentListeners = []
let nextListeners = currentListeners
let isDispacthing = false
function ensureCaneMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice()
}
}
function getState() {
return currentState
}
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.')
}
let isSubscribed = true
ensureCanMutateNextListeners()
nextListeners.push(listener)
return function unsubscribe() {
if (!isSubscribed) {
return
}
isSubscribed = false
ensureCanMutateNextListeners()
const index = nextListeners.indexOf(listener)
nextListeners.splice(index, 1)
}
}
function dispatch(action) {
if (isDispacthing) {
throw new Error('Reducers may not dispatch actions.')
}
isDispacthing = true
currentState = currentReducer(currentState, action)
const listeners = currentListeners = nextListeners
for (var i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
}
return action
}
return {
dispatch,
getState
}
}
const logReducer = (initState = {}, action) => {
switch (action.type) {
case "load":
console.log(action)
break;
default:
console.log('default')
}
}
const load = (name) => {
return {
type: 'load',
playload: name
}
}
const createStoreWithMiddleware = applayMiddleware(thunk, log)(createStore)
let store = createStoreWithMiddleware(logReducer)
console.log(store)
store.dispatch(load('haha'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.