image.png

createStore

返回一个对象:

  • dispatch:分发一个action
  • getState:得到仓库中当前的状态
  • subscribe:注册一个监听器,监听器是一个无参函数,该分发一个action之后,会运行注册的监听器。该函数会返回一个函数,用于取消监听
  1. /**
  2. *
  3. * @param {*} obj 对象
  4. * @returns 判断是否是平面对象
  5. */
  6. function isPlainObject(obj) {
  7. if (typeof obj !== 'object') {
  8. return false;
  9. }
  10. return Object.getPrototypeOf(obj) === Object.prototype;
  11. }
  12. /**
  13. *
  14. * @param {*} length
  15. */
  16. function RandomStr(length) {
  17. return Math.random().toString(36).substr(2, length).split('').join('.')
  18. }
  19. /**
  20. *
  21. * @param {*} reducer
  22. * @param {*} defaultState
  23. * @returns
  24. */
  25. export default function (reducer, defaultState) {
  26. let currState = defaultState,
  27. currReducer = reducer;
  28. const listeners = [];
  29. function dispatch(action) {
  30. // 判断action是平面对象
  31. if (!isPlainObject(action)) {
  32. throw TypeError('action must be a plain objet')
  33. }
  34. if (action.type === undefined) {
  35. throw TypeError('action must be have property of type')
  36. }
  37. currState = currReducer(currState, action);
  38. for (const listener of listeners) {
  39. listener();
  40. }
  41. }
  42. function getState() {
  43. return currState;
  44. }
  45. function subscribe(listener) {
  46. listeners.push(listener);
  47. let isRemove = false;
  48. return function () {
  49. if (isRemove) {
  50. return;
  51. }
  52. const index = listeners.indexOf(listener);
  53. listeners.splice(index, 1);
  54. isRemove = true;
  55. console.log('listeners', listeners)
  56. }
  57. }
  58. dispatch({
  59. type: `@@redux/INIT${RandomStr()}`
  60. })
  61. return {
  62. dispatch,
  63. getState,
  64. subscribe
  65. }
  66. }