redux入门 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

disptch函数实现

这一节我们将学习dispatch是如何工作的。

1、disptch?Reducer?

我们所看到的 dispatch 函数是 Redux 提供的,并且它会将 action 传递给任何一reducer!dispatch 函数本质上是 Redux的实例的属性 "dispatch",因为我们可以在源码中找到currentState = currentReducer(currentState, action);

代码:

function dispatch(action) {
    //...
    try {
      isDispatching = true;
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }
    //...

2、listener函数的使用

上一小节我们提到了subscribe对listener函数的处理,却没有提到他会在哪使用,我想到现在大家应该都明白了,listener就是在dispatch中使用的。dispatch通过一个for循环将每个listener运行

代码:

function dispatch(action) {
    //...
    try {
      isDispatching = true;
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }
    var listeners = currentListeners = nextListeners;
    for (var i = 0; i < listeners.length; i++) {
      listeners[i]();
    }
    return action;
}