Redux和长时间运行的异步任务

时间:2019-04-09 14:50:04

标签: reactjs asynchronous redux websocket redux-thunk

我有一个React SPA,Redux备份了我的状态。我想向服务器提交一个长期运行的任务并获得定期更新(例如加载栏或纯文本)。通过WebSockets进行通信。在Redux中以结构方式构造此结构的推荐方法是什么?

为了清楚起见,我们添加了一些代码,TODO是我不知道该怎么做的地方

// Render 

<LoadingBar show={this.props.showLoadingBar} progress={this.props.progress} /> // From redux store connect
<button onClick={store.dispatch(startLongRunningProcess())} />

// Action

function startLongRunningProcess() {
    // TODO: Should I open my web socket here?
    return {
        action: START_LONG_RUNNING_PROCESS,
        payload: null,
    }
}

// Reducer

export default (state=initialState, action) => {
    switch(action.type) {
    case START_LONG_RUNNING_PROCESS: {
        return {
            ...state,
            showLoadingBar: true,
        }
    }
    // TODO: Where do I dispatch this guy?
    case FINISH_LONG_RUNNING_PROCESS: {
        return {
            ...state,
            showLoadingBar: false,
        }
    }
    // TODO: Where do I dispatch this guy?
    case PROGRESS_UPDATE_FROM_SERVER: {
        return {
            ...state,
            progress: action.payload.progress,
        }
    }
};

我很乐意将更多库(也许是redux-thunk)添加到我的依赖项列表中。

谢谢!

1 个答案:

答案 0 :(得分:0)

在这种情况下,我认为您不会被迫使用componentDidMount(){ axios.get('/api/path-you-want').then(response=>{ console.log(response) }) } 或类似的库。只需在使用Websocket的任何位置导入商店,然后使用用于更新商店的操作调用redux-thunk。您的情况就足够了。

相关问题