简体   繁体   English

如何将商店连接到异步Redux操作

[英]How to Redux connect store to an async Redux action

I have an async action fetchTasks which is given a list of tasks, and sends a request for each task (these may or may not take a while to finish). 我有一个异步操作fetchTasks ,该操作被赋予任务列表,并为每个任务发送请求(这些操作可能会或可能不会花一些时间才能完成)。 I want my front end to only be able to send 5 requests at a time. 我希望我的前端一次只能发送5个请求。 Since many components have Ajax functionality, I decided to implement the request counter within the redux store. 由于许多组件都具有Ajax功能,因此我决定在redux存储中实现请求计数器。 The value is called fetchCount , and is used by many components to see if they want to allow the user to send a request. 该值称为fetchCount ,许多组件使用该值来查看它们是否要允许用户发送请求。

Now the issue is fetchTasks can get more than 5 tasks in the task list. 现在的问题是fetchTasks可以在任务列表中获取5个以上的任务。 I've dealt with that by first sending requests until the fetchCount reaches 0, then I recursively call fetchTasks whenever a server response is received for a fetch. 我已经通过先发送请求直到fetchCount达到0来处理此问题,然后每当收到服务器的响应以进行提取时,我便递归调用fetchTasks

function fetchTasks(taskList){
    return dispatch => {
         while(taskList.length > 0 && fetchCount > 0){ // <-- I need fetchCount to be up to date with the store
           decrementFetchCount(); //a redux action
           let task = taskList.pop();
           $ajax({
               url: `/do/${task}`,
               success:(data)=>{
                 processData(data); // redux action
                 incrementFetchCount(); // a redux action
                 dispatch(fetchTasks(taskList));
                } 
            });
        }
    }
}

My issue is that I need fetchTasks to be aware of the value of fetchCount at any point in its run time. 我的问题是,我需要fetchTasks要意识到的价值fetchCount在其运行的任意时间点。 I'm thinking that connecting it to the store is the key, but I don't know how to connect a function to the store. 我以为将其连接到商店是关键,但是我不知道如何将功能连接到商店。 Therein lies the problem. 问题就出在这里。 Also, this smells. 另外,这闻起来。 If someone has an alternative way to implement this that they want to suggest, that would also be a valid answer. 如果某人有其他建议的实现方式,那也是一个有效的答案。

I'm assuming this is using redux-thunk . 我假设这是使用redux-thunk You can have a second paramenter getState together with dispatch . 您可以将第二个参数getStatedispatch一起使用。

You fetchTasks would look something like this... fetchTasks看起来像这样...

function fetchTasks(taskList) {
    return (dispatch, getState) => {
        while (taskList.length > 0 && getState().fetchCount > 0) {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM