How to replicate onDidBlur or onWillBlur with React Navigation 5?

限于喜欢 提交于 2021-01-01 17:53:09

问题


As they point out in the docs, they've gotten rid of the 4 navigation event listeners and instead decided to use Lifecycle events.

But the problem I'm running into with React Navigation 5 is that the blur event doesn't work as I need it to! Before, I could add an onWillBlur listener, and do stuff when the user temporarily leaves (not closes) the app (such as close a socket connection, and then reopen it when the user reenters the app).

How can I replicate the onWillBlur or onDidBlur events for such a use case? I don't need to know if Screen A is blurred after the user is taken to Screen B after clicking a button.


回答1:


You can use the hook useFocusEffect.

Documentation here

EDIT:

Added example from React Navigation.

import { useFocusEffect } from '@react-navigation/native';

function Profile() {
  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused, onFocus


      return () => {
        // Do something when the screen is unfocused, onBlur
        // Useful for cleanup functions
      };
    }, [])
  );

  return <ProfileContent />;
}

EDIT 2:

I didn't test it on home button but I found a post that helps with that too

Check here

I hope this time you are pleased with my answer.

And here you have a working example :

import React from 'react'
import { Text, AppState } from 'react-native'

const MyComponent = () => {

    const [appState, setAppState] = React.useState(AppState.currentState)

    React.useEffect(() => {
      AppState.addEventListener('change', handleChanges)

      setAppState(AppState.currentState)

      return AppState.removeEventListener('change')
    },[])

    const handleChanges = (nextAppState) => {
        if (appState.match(/inactive|background/) && nextAppState === 'active') {

          console.log('App has come to the foreground!');
        } else {
          console.log('App has gone to the background!');
          // start your background task here
        }

        setAppState(nextAppState)
    }

    return  <Text>{appState}</Text>
}


来源:https://stackoverflow.com/questions/61370290/how-to-replicate-ondidblur-or-onwillblur-with-react-navigation-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!