跳到主要内容

 

setupListeners

这是一个用于启用 refetchOnFocusrefetchOnReconnect 行为的实用工具。它需要你的存储中的 dispatch 方法。调用 setupListeners(store.dispatch) 将使用推荐的默认值配置监听器,但你也可以提供一个回调函数以进行更精细的控制。

setupListeners 默认配置
let initialized = false
export function setupListeners(
dispatch: ThunkDispatch<any, any, any>,
customHandler?: (
dispatch: ThunkDispatch<any, any, any>,
actions: {
onFocus: typeof onFocus
onFocusLost: typeof onFocusLost
onOnline: typeof onOnline
onOffline: typeof onOffline
},
) => () => void,
) {
function defaultHandler() {
const handleFocus = () => dispatch(onFocus())
const handleFocusLost = () => dispatch(onFocusLost())
const handleOnline = () => dispatch(onOnline())
const handleOffline = () => dispatch(onOffline())
const handleVisibilityChange = () => {
if (window.document.visibilityState === 'visible') {
handleFocus()
} else {
handleFocusLost()
}
}

if (!initialized) {
if (typeof window !== 'undefined' && window.addEventListener) {
// 处理焦点事件
window.addEventListener(
'visibilitychange',
handleVisibilityChange,
false,
)
window.addEventListener('focus', handleFocus, false)

// 处理连接事件
window.addEventListener('online', handleOnline, false)
window.addEventListener('offline', handleOffline, false)
initialized = true
}
}
const unsubscribe = () => {
window.removeEventListener('focus', handleFocus)
window.removeEventListener('visibilitychange', handleVisibilityChange)
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
initialized = false
}
return unsubscribe
}

return customHandler
? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline })
: defaultHandler()
}

如果你注意到,onFocusonFocusLostonOfflineonOnline 都是提供给回调的操作。此外,这些操作都可以通过 api.internalActions 使用,并且可以通过像这样分派它们来使用:

手动 onFocus 事件
dispatch(api.internalActions.onFocus())