【问题标题】:Synchronous Redux Actions同步 Redux 操作
【发布时间】:2017-09-29 17:32:34
【问题描述】:

我正在尝试在 Redux 中进行同步调度调用,其中第一次调用更新 isLoading 状态,以便我们可以在 UI 上显示加载图标,然后第二次调用在后台执行大量同步计算以更新项目位置 - 大约需要 2-5 秒。

第一个动作发生并且状态被正确更改,但似乎在那之后立即发生它并没有击中反应前端组件,而是进入第二个调度。当我在第一次调度后添加一个简短的timeout 时它可以工作,但我讨厌硬编码一个固定的等待时间。

这个问题有更好的解决方案吗?

不工作:

const showLoadingIcon = () => ({type: types.SHOW_LOADING_ICON});
export const updateInteractionTypeScores = (updatedValues) => dispatch => {
    dispatch(showLoadingIcon());
    dispatch({type: types.UPDATE_VALUES, updatedValues});
};

工作:

const showLoadingIcon = () => ({type: types.SHOW_LOADING_ICON});
export const updateInteractionTypeScores = (updatedValues) => dispatch => {
    dispatch(showLoadingIcon());
    setTimeout(() => dispatch({type: types.UPDATE_VALUES, updatedValues}), 100);
};

【问题讨论】:

    标签: redux react-redux redux-thunk


    【解决方案1】:

    你所说的同步动作实际上一个异步动作,在特定时间更新存储。此类事情的一般模式是(至少)为每个动作状态分配三个调度。

    1. 异步操作启动
    2. 异步操作成功
    3. 异步操作失败

    启动异步操作会分派一个“ASYNC_ACTION_LAUNCHED”操作,该操作会更新您的组件已正确连接到的商店(对吗?),因此将显示加载图标。

    成功后,会发送“ASYNC_ACTION_SUCCESS”,更新存储,组件使用新的存储内容重新呈现。

    失败时,会发送“ASYNC_ACTION_FAILURE”,更新存储,使用空内容和错误消息重新渲染组件。

    实际上,这相当于更多的代码,但这允许更多的可能性:

    const asyncActionLaunched = () => ({type: types.ASYNC_ACTION_STARTED});
    const asyncActionSuccess = () => ({type: types.ASYNC_ACTION_SUCCESS});
    const asyncActionFailed = () => ({type: types.ASYNC_ACTION_FAILED});
    
    export const updateInteractionTypes = dispatch => {
        dispatch(asyncActionLaunched());
    
        // I don't know your setup
        // But this whould either be a Promise, or return a boolean
    
        // in the case of a synchronous function
        const result = makeSynchronousCalculations();
        if (result) {
            dispatch(asyncActionSuccess());
            // dispatch another action that updates store
        } else {
            dispatch(asyncActionFailed());
            // dispatch another action that updates store
        }
        // in the case of a promise
        asyncBlockingAction()
            .then(
                dispatch(asyncActionSuccess());
                // dispatch another action that updates store
            ).catch(
                dispatch(asyncActionFailed());
                // dispatch another action that updates store
            );
    };
    

    【讨论】:

    • 啊,这完全有道理,应该很好用......谢谢!
    猜你喜欢
    • 2020-04-23
    • 2017-08-19
    • 2017-09-26
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多