【问题标题】:How to launch a dispatch after the previous ends如何在前一个结束后启动调度
【发布时间】:2018-12-18 08:29:09
【问题描述】:

首先,感谢您阅读我的问题并尝试帮助我并为我的英语道歉。

我正在使用 redux 和 redux-thunk,我想在 redux 上启动多个调度。更准确地说,我想在前一个结束后启动一个调度。

我的问题是我不知道如何在没有 fetch 的情况下制作它。

例如: 启动 dispatch1 -> 结束 dispatch1 -> 启动 dispatch2

这是我的代码:

static moveLayer(layerSelected, direction) {
    const mapLayers = [... AxisStore.getStore().getState().map.mapGLlayers];
    const ids = mapLayers.map(l => l.id);
    const index = ids.indexOf(layerSelected.id);
    let newIndex = direction === 'down' ? index - 1 : index + 1;

    let layerUpdated = Object.assign({}, mapLayers[index], {
        redraw: false
    });
    let oldPositionLayer = Object.assign({}, mapLayers[newIndex], {
        redraw: false
    });

    if (direction === 'down') {
        mapLayers.splice(newIndex, 2, layerUpdated, oldPositionLayer);
    } else {
        mapLayers.splice(index, 2, oldPositionLayer, layerUpdated);
    }

    return (dispatch) => {
        dispatch({
            type: MapTypeConstants.SET_MAP_LAYERS,
            payload: mapLayers
        });
    };
}

static updateBefore(layer) {
    let mapLayers = [... AxisStore.getStore().getState().map.mapGLlayers];
    const ids = mapLayers.map(l => l.id);
    const posInRedux = ids.indexOf(layer.id);
    let nextVisibleLayer = mapLayers.find((layerObj, idx) => idx > posInRedux && layerObj.layout && layerObj.layout.visibility && layerObj.layout.visibility === 'visible');
    mapLayers[posInRedux].before = (nextVisibleLayer) ? String(nextVisibleLayer.id) : undefined;
    mapLayers[posInRedux].redraw = (mapLayers[posInRedux].layout.visibility === 'visible') ? true : false;
    return (dispatch) => {
        dispatch({
            type: MapTypeConstants.SET_MAP_LAYERS,
            payload: mapLayers
        });
    };
}

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    要等待异步调用结束,您可以使用 JS 关键字 await。使用此关键字时,您的代码将暂停,直到您调用的 Promise 结束,您的函数现在也需要变为 async

    myFunction = async () => {
        await dispatch({})
        dispatch({})
    }
    

    除非第一个调度完成,否则不会调用您的第二个调度。

    这是你唯一的方法,请参阅下面的评论

    第二种选择是使用Promise.all。它会按照你提交的顺序执行一个 Promises 数组:

    myFunction = async () => {
        await Promises.all([
            dispatch({}),
            dispatch({})
        ])
    }
    

    【讨论】:

    • Promises.all 确实并行执行承诺,而不是顺序执行!
    【解决方案2】:

    您可以尝试redux-loop,它完全符合您的要求。

    Elm 架构到 Redux 的一个端口,它允许您通过从 reducer 返回它们来自然而纯粹地对效果进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2022-11-29
      相关资源
      最近更新 更多