2017-04-05 7 views
7

我正在使用REDX事件通道。我有一個特定的用例,當事件被觸發時,我想要getStore狀態,因爲eventChannel不是生成器函數,我不能使用Redux傳說的選擇效果。任何其他方式來實現這一目標?在正常功能/事件中使用select效果通道

我也曾嘗試導入商店並使用store.getState()但我得到undefined,因爲saga文件是在商店初始化之前導入的。

function subscribe(socket) { 
    return eventChannel(emit => { 
     socket.subscribe(listenerTopic, {qos: 1}); 
     socket.on('reconnection',() => { 
      // i need to fetch latest unread message, for that i need to get timestamp 
      // for last message received which is in store so the command will be to 
     // send sinceDate i.e last message timestamp and untilDate that is currentDate 
    }) 
} 
+0

該解決方案可能涉及將某些邏輯從eventEmitter函數移動到執行其操作的傳奇。你能分享一些代碼,以便我們可以看到eventEmitter/saga正在做什麼事情嗎? – VonD

+0

我的用例是 我需要在連接恢復時獲取最新的未讀消息,因爲我需要獲取時間戳 收到的最後一條消息,這是存儲在這樣的命令將 發送sinceDate即上一個消息時間戳,並untilDate是currentDate –

回答

1

一個可能的解決方案是使用redux-saga通道功能。 這個想法是每次發生套接字事件時將事件插入通道。與此同時,你還有另一個傳奇人物傾聽頻道上的事件並作出相應反應。由於聽力部分是一個傳奇故事,你可以使用常見的傳奇效果,如select

您的代碼可能看起來是這樣的:

import { channel } from 'redux-saga' 
import { select } from 'redux-saga/effects' 

const socketChannel = channel() 

function subscribe(socket) { 
    return eventChannel(emit => { 
    socket.on('reconnection',() => { 
     socketChannel.put({ type: RECONNECTION }) 
    }) 
    }) 
} 

export function* watchSocketChannel() { 
    while (true) { 
    const action = yield take(socketChannel) 

    if (action.type === RECONNECTION) { 
     const lastMessageTimestamp = yield select(selectors.getLastMessageTimestamp) 
     ... 
    } 
    } 
} 

我希望這會幫助你。