Skip to content

Commit

Permalink
简化 useVisibleEffect 的实现
Browse files Browse the repository at this point in the history
  • Loading branch information
listenzz committed Oct 31, 2023
1 parent bb8f51d commit 8be1a1b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 30 deletions.
22 changes: 22 additions & 0 deletions docs/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,28 @@ useVisibleEffect(

如果需要获取页面可见状态,使用 `useVisible` 或者 `useVisibility`

```ts
import React, { useEffect } from 'react'
import { useVisible } from 'hybrid-navigation'

const MyComponent = () => {
const visible = useVisible()

useEffect(() => {
if (!visible) {
return
}
console.info('页面可见')

return () => {
console.info('页面不可见')
}
}, [visible])

return <View />
}
```

## 类组件

本项目中的例子几乎都是用函数组件示例的,因为这是趋势,历史的车轮滚滚向前,该忘掉的就忘掉,该丢弃的就丢弃。
Expand Down
43 changes: 13 additions & 30 deletions src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import React, { useContext, useEffect, useRef, useState } from 'react'
import React, { useContext, useEffect, useState } from 'react'
import Navigation from './Navigation'
import { Navigator, NavigationContext } from './Navigator'

export function useVisible() {
const visibility = useVisibility()
return visibility === 'visible'
export function useNavigator(): Navigator {
return useContext<Navigator>(NavigationContext)
}

export function useVisibility() {
Expand All @@ -21,34 +20,18 @@ export function useVisibility() {
return visibility
}

export function useVisibleEffect(effect: React.EffectCallback) {
const navigator = useNavigator()
const destructor = useRef<ReturnType<React.EffectCallback>>()

useEffect(() => {
if (navigator.visibility === 'visible') {
destructor.current = effect()
}

const subscription = Navigation.addVisibilityEventListener(navigator.sceneId, visibility => {
if (visibility === 'visible') {
destructor.current = effect()
} else {
destructor.current && destructor.current()
destructor.current = undefined
}
})

return () => {
destructor.current && destructor.current()
destructor.current = undefined
subscription.remove()
}
}, [effect, navigator])
export function useVisible() {
const visibility = useVisibility()
return visibility === 'visible'
}

export function useNavigator(): Navigator {
return useContext<Navigator>(NavigationContext)
export function useVisibleEffect(effect: React.EffectCallback) {
const visible = useVisible()
useEffect(() => {
if (!visible) return
const destructor = effect()
return () => destructor && destructor()
}, [effect, visible])
}

/**
Expand Down

0 comments on commit 8be1a1b

Please sign in to comment.