javascript - 如何在 redux 操作中每次执行多个函数时仅使用一个循环

标签 javascript reactjs redux frontend

所以,我有一个 Redux-action 在我的应用程序中被多次调用,本质上我需要的是每次调用该操作时,它只需使用操作中传递的新数据重置 setInterval 10 秒.

export function fetchInterviewer(lastInterviewerId, interviewId, phone) {
    setInterval(()=>{
        fetchInterviewerLoop(lastInterviewerId, interviewId, phone);
    },10000)
}

export function fetchInterviewerLoop(lastInterviewerId, interviewId, phone){
    Store.dispatch(interviewerIsLoading(callId));

    let p = phone && SystemService.decodePhone(phone);

    return {
        type: CALL_FETCH_INTERVIEWER,
        payload: HttpService.get(`${lastInterviewerId}/interview/${interviewId}/interviewer?phone=${p}`)
    }
}

问题是,每次在应用程序中调用 fetchInterviewer 时,它不仅仅是重新启动该函数,它只是创建一个新的单独循环实例,因此我可以调用该操作 10 次,然后我将有 10不同的循环。

我尝试了多种不同的方法,但我觉得答案可能是那么小而愚蠢。

最佳答案

如果您不想停止间隔,您可以使用引用循环参数的对象:

let paramsRef;
let interval;
export function fetchInterviewer(lastInterviewerId, interviewId, phone) {
    paramsRef =  {lastInterviewerId, interviewId, phone}
    if(!interval){
        interval = setInterval(()=>{
            const {lastInterviewerId, interviewId, phone} = paramsRef
            fetchInterviewerLoop(lastInterviewerId, interviewId, phone);
        },10000)
    }
}

export function fetchInterviewerLoop(lastInterviewerId, interviewId, phone){
    Store.dispatch(interviewerIsLoading(callId));

    let p = phone && SystemService.decodePhone(phone);

    return {
        type: CALL_FETCH_INTERVIEWER,
        payload: HttpService.get(`${lastInterviewerId}/interview/${interviewId}/interviewer?phone=${p}`)
    }
}

关于javascript - 如何在 redux 操作中每次执行多个函数时仅使用一个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507342/

相关文章:

javascript - Fiber 中的空变量

javascript - 如何在 HTML 选择选项列表中保留空间<option value ='hi this' >hi</option>

reactjs - 当位置改变时重新定位 map 中心?

reactjs - react native map 标记不显示

javascript - 从 Firebase 获取数据时,来自 Redux Toolkit 的 createAsyncThunk 会产生未定义的负载

javascript - 如何将变量插入到html src中?

javascript - Leaflet 和 MapBox API - 遵循地球形状的曲线

javascript - 如何在时间戳数组中保留唯一的月份

javascript - 如果用户在使用 react-navigation 打开应用程序时未登录,则显示登录屏幕

javascript - "dispatch"未捕获类型错误 React-Redux