簡體   English   中英

RxJS 輪詢服務器並使用新數據更新應用程序 state

[英]RxJS poll server and update application state with new data

服務器node.js每 0.5 秒更新一次數據。 客戶端必須輪詢服務器並使用RxJS獲取新數據。 我已經讓客戶端輪詢服務器,請求已發出,但我無法讀取服務器的響應。 我認為 state 沒有更新,因為poll_server返回timer.pipe()或者減速器創建了錯誤的 state。 我是從老師的模板中得出這個結論的,那么為什么調度員會返回一個Observable呢?

model.js

export function init_state(warnings) {
    return {
        warnings,
        accept: ({ visit_site }) => { if (visit_site) return visit_site(warnings) }
    }
}

調度程序.js

import { from, of, timer } from 'rxjs'
import { concatMap, map } from 'rxjs/operators'
import { FRONT_PAGE } from './constants'

const poll_server = url => {
    return timer(0, 3000)
        .pipe(concatMap(() => from(fetch(url))
            .pipe(map(response => response.json())))
        )
}

export const server_dispatch = action => {
    switch (action.type) {
        case FRONT_PAGE: {
            const res = poll_server('http://localhost:8080/warnings')
            console.log(res)
            return res
        }
        default:
            return of(action)
    }
}

減速器.js

export function reduce(state, action) {
    switch (action.type) {
        case FRONT_PAGE:
            console.log(`REDUCER CALLED WITH ACTION ${FRONT_PAGE}`)
            return init_state(action)
        default:
            return state
    }
}

The problem is that you want to call poll_server which will start an observable stream on an ajax endpoint from within the reducer (which implies you would subscribe to this stream here, not the way you are currently using it), which isn't how redux應該是使用的。 Reducers 的創建者打算將其作為純函數而不會產生副作用。

如果您想將 redux 與 observables 一起使用,建議使用自定義中間件來處理這些副作用。 我建議的最明顯的中間件是https://redux-observable.js.org/ ,我過去曾嘗試過並且可以正常工作。

文檔很精致,如果您已經熟悉 RX 原理,您將毫無困難地使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM