Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Created March 24, 2021 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongyangxun/151186962c17bc710a6a532f1b0ebb12 to your computer and use it in GitHub Desktop.
Save zhongyangxun/151186962c17bc710a6a532f1b0ebb12 to your computer and use it in GitHub Desktop.
手写简易 Redux
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