Created
March 24, 2021 14:39
-
-
Save zhongyangxun/151186962c17bc710a6a532f1b0ebb12 to your computer and use it in GitHub Desktop.
手写简易 Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createStore(state, reducer) { | |
const listeners = []; | |
const getState = () => state; | |
const dispatch = (action) => { | |
state = reducer(state, action); | |
listeners.forEach((item) => item()); | |
} | |
const subscribe = (fn) => listeners.push(fn); | |
return { | |
getState, | |
dispatch, | |
subscribe, | |
}; | |
} | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'UPDATE_NAME': | |
return { | |
...state, | |
name: action.payload, | |
} | |
case 'UPDATE_AGE': | |
return { | |
...state, | |
age: action.payload, | |
} | |
default: | |
return state; | |
} | |
}; | |
const store = createStore({ | |
name: 'Jack', | |
age: 18, | |
}, reducer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment