2019-11-16 08:36 小维FE 阅读() 评论() 编辑 收藏

作者:Yazeed Bzadough
译者:小维FE
原文:freecodecamp

为了保证文章的可读性,本文采用意译而非直译。

90%的规约,10%的库。
Redux是迄今为止创建的最重要的JavaScript库之一,灵感来源于以前的艺术比如FluxElm,Redux通过引入一个包含三个简单要点的可伸缩体系结构,使得JavaScript函数式编程成为可能。如果你是初次接触Redux,可以考虑先阅读官方文档

考虑如下这个使用了Redux架构的简单的计数器应用。如果你想跳过的话可以直接查看Github Repo

该应用程序的状态看起来如下:

  1. const initialState = { count: 0 };

根据Redux规约,我们不直接修改(突变)状态。

  1. // 在Redux应用中不要做如下操作
  2. state.count = 1;

相反,我们创建在应用中用户可能用到的所有行为。

  1. const actions = {
  2. increment: { type: 'INCREMENT' },
  3. decrement: { type: 'DECREMENT' }
  4. };

在最后一个架构部分我们叫做Reduer,其作为一个纯函数,它基于以前的状态和行为返回状态的新副本。

  • 如果increment被触发,则增加state.count
  • 如果decrement被触发,则减少state.count
  1. const countReducer = (state = initialState, action) => {
  2. switch (action.type) {
  3. case actions.increment.type:
  4. return {
  5. count: state.count + 1
  6. };
  7. case actions.decrement.type:
  8. return {
  9. count: state.count - 1
  10. };
  11. default:
  12. return state;
  13. }
  14. };

你注意到了吗?到目前为止我们甚至还没有接触到Redux库,我们仅仅只是创建了一些对象和函数,这就是为什么我称其为”大多是规约”,90%的Redux应用其实并不需要Redux。

要使用这种架构,我们必须要将它放入到一个store当中,我们将仅仅实现一个函数:createStore。使用方式如下:

  1. import { createStore } from 'redux'
  2. const store = createStore(countReducer);
  3. store.subscribe(() => {
  4. console.log(store.getState());
  5. });
  6. store.dispatch(actions.increment);
  7. // logs { count: 1 }
  8. store.dispatch(actions.increment);
  9. // logs { count: 2 }
  10. store.dispatch(actions.decrement);
  11. // logs { count: 1 }

下面这是我们的初始化样板代码,我们需要一个监听器列表listeners和reducer提供的初始化状态。

  1. const createStore = (yourReducer) => {
  2. let listeners = [];
  3. let currentState = yourReducer(undefined, {});
  4. }

无论何时某人订阅了我们的store,那么他将会被添加到listeners数组中。这是非常重要的,因为每次当某人在派发(dispatch)一个动作(action)的时候,所有的listeners都需要在此次事件循环中被通知到。调用yourReducer函数并传入一个undefined和一个空对象将会返回一个initialState,这个值也就是我们在调用store.getState()时的返回值。既然说到这里了,我们就来创建这个方法。

这个函数用于从store中返回最新的状态,当用户每次点击一个按钮的时候我们都需要最新的状态来更新我们的视图。

  1. const createStore = (yourReducer) => {
  2. let listeners = [];
  3. let currentState = yourReducer(undefined, {});
  4. return {
  5. getState: () => currentState
  6. };
  7. }

这个函数使用一个action作为其入参,并且将这个actioncurrentState反馈给yourReducer来获取一个新的状态,并且dispatch方法还会通知到每一个订阅了当前store的监听者。

  1. const createStore = (yourReducer) => {
  2. let listeners = [];
  3. let currentState = yourReducer(undefined, {});
  4. return {
  5. getState: () => currentState,
  6. dispatch: (action) => {
  7. currentState = yourReducer(currentState, action);
  8. listeners.forEach((listener) => {
  9. listener();
  10. });
  11. }
  12. };
  13. };

这个方法使得你在当store接收到一个action的时候能够被通知到,可以在这里调用store.getState()来获取最新的状态并更新UI。

  1. const createStore = (yourReducer) => {
  2. let listeners = [];
  3. let currentState = yourReducer(undefined, {});
  4. return {
  5. getState: () => currentState,
  6. dispatch: (action) => {
  7. currentState = yourReducer(currentState, action);
  8. listeners.forEach((listener) => {
  9. listener();
  10. });
  11. },
  12. subscribe: (newListener) => {
  13. listeners.push(newListener);
  14. const unsubscribe = () => {
  15. listeners = listeners.filter((l) => l !== newListener);
  16. };
  17. return unsubscribe;
  18. }
  19. };
  20. };

同时subscribe函数返回了另一个函数unsubscribe,这个函数允许你当不再对store的更新感兴趣的时候能够取消订阅。

现在我们添加按钮的逻辑,来看看最后的源代码:

  1. // 简化版createStore函数
  2. const createStore = (yourReducer) => {
  3. let listeners = [];
  4. let currentState = yourReducer(undefined, {});
  5. return {
  6. getState: () => currentState,
  7. dispatch: (action) => {
  8. currentState = yourReducer(currentState, action);
  9. listeners.forEach((listener) => {
  10. listener();
  11. });
  12. },
  13. subscribe: (newListener) => {
  14. listeners.push(newListener);
  15. const unsubscribe = () => {
  16. listeners = listeners.filter((l) => l !== newListener);
  17. };
  18. return unsubscribe;
  19. }
  20. };
  21. };
  22. // Redux的架构组成部分
  23. const initialState = { count: 0 };
  24. const actions = {
  25. increment: { type: 'INCREMENT' },
  26. decrement: { type: 'DECREMENT' }
  27. };
  28. const countReducer = (state = initialState, action) => {
  29. switch (action.type) {
  30. case actions.increment.type:
  31. return {
  32. count: state.count + 1
  33. };
  34. case actions.decrement.type:
  35. return {
  36. count: state.count - 1
  37. };
  38. default:
  39. return state;
  40. }
  41. };
  42. const store = createStore(countReducer);
  43. // DOM元素
  44. const incrementButton = document.querySelector('.increment');
  45. const decrementButton = document.querySelector('.decrement');
  46. // 给按钮添加点击事件
  47. incrementButton.addEventListener('click', () => {
  48. store.dispatch(actions.increment);
  49. });
  50. decrementButton.addEventListener('click', () => {
  51. store.dispatch(actions.decrement);
  52. });
  53. // 初始化UI视图
  54. const counterDisplay = document.querySelector('h1');
  55. counterDisplay.innerHTML = parseInt(initialState.count);
  56. // 派发动作的时候跟新UI
  57. store.subscribe(() => {
  58. const state = store.getState();
  59. counterDisplay.innerHTML = parseInt(state.count);
  60. });

我们再次看看最后的视图效果:

原文: https://www.freecodecamp.org/news/redux-in-24-lines-of-code/

本篇主要简单了解下Redux的三个架构组成部分以及如何实现一个简化版的Redux,对Redux能有进一步的了解,希望能和大家相互讨论技术,一起交流学习。

文章已同步更新至Github博客,若觉文章尚可,欢迎前往star!

你的一个点赞,值得让我付出更多的努力!

逆境中成长,只有不断地学习,才能成为更好的自己,与君共勉!

版权声明:本文为tangshiwei原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/tangshiwei/p/11870517.html