【问题标题】:React Native: Active state in AppState listener getting triggered when component mountsReact Native:当组件挂载时,AppState 监听器中的活动状态被触发
【发布时间】:2020-04-26 01:17:48
【问题描述】:

我在 React Native 中为 AppState 设置了一个监听器,以了解我的应用何时从后台切换到前台,以便显示启动画面。

useEffect(() => {
AppState.addEventListener('change', handleAppStateChange);
},[])

const handleAppStateChange = newState => {

    if (newState === 'active') {
      RNBootSplash.show();
    }

  };

问题是,这仅在我编译发布 APK 时发生,由于某种原因,它在调试中工作正常,每次安装组件时都会显示启动画面,而它应该只在应用程序切换到来自后台的活动状态。有什么帮助吗?

使用 React Native 61.5

【问题讨论】:

    标签: android reactjs react-native


    【解决方案1】:

    试试这个方法:

    const [appState, setAppState] = React.useState(AppState.currentState)
    
    useEffect(() => {
        AppState.addEventListener('change', handleAppStateChange)
    
        setAppState(AppState.currentState)
    
        return AppState.removeEventListener('change')
    },[])
    
    const handleAppStateChange = newState => {
        if (appState.match(/inactive|background/) && newState === 'active') {
          console.log('App has come to the foreground!')
          // Show the splash screen
          RNBootSplash.show()
        } else {
          console.log('App has gone to the background!')
          // do something in background
        }
    
        setAppState(newState)
    }
    

    【讨论】:

    • 我试过了,但无论我做什么,handleAppStateChange 中的 appState 都不会改变它的默认值。我什至尝试过 useCallback 并将 appState 放入依赖数组中,但 nada。唯一有效的是使用 useRef 而不是 useState。
    【解决方案2】:

    唯一有效的方法是使用 refs

    const latestAppState = React.useRef(AppState.currentState)
    
    const handleAppStateChange = newState => {
    
        if (latestAppState.current.match(/inactive|background/) && newState === 'active') {
          RNBootSplash.show();
    
        }
        latestAppState.current = newState
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      相关资源
      最近更新 更多