setupListeners
一个用于启用 refetchOnFocus
和 refetchOnReconnect
行为的实用程序。它需要来自您的存储的 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) {
// Handle focus events
window.addEventListener(
'visibilitychange',
handleVisibilityChange,
false,
)
window.addEventListener('focus', handleFocus, false)
// Handle connection events
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()
}
如果您注意到,onFocus
、onFocusLost
、onOffline
、onOnline
都是提供给回调的 action。此外,这些 action 可用于 api.internalActions
,并且可以通过以下方式进行调度
手动 onFocus 事件
dispatch(api.internalActions.onFocus())