简体   繁体   中英

React-Navigation: Call function whenever page is navigated to

I am developing a React-Native app using React-Navigation, and I am using a stack navigator.

How can I call a function whenever a page is navigated to, including on goBack() events? If I place the method in my constructor, it is only triggered on its initial creation, and not when it is attained through goBack().

use Navigation Events I believe you can use did focus and will blur

<NavigationEvents
      onWillFocus={payload => console.log('will focus', payload)}
      onDidFocus={payload => console.log('did focus', payload)}
      onWillBlur={payload => console.log('will blur', payload)}
      onDidBlur={payload => console.log('did blur', payload)}
    />

https://reactnavigation.org/docs/en/navigation-events.html

EDIT 2021

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

const isFocused = useIsFocused();

React.useEffect(()=>{
 if(isFocused){

   // callback
 }
},[isFocused])

As you noted the component is never unmounted when changing pages, so you can't rely on the constructor or even componentDidMount . There is a lot of discussion about this topic in this issue .

You could eg listen to the didFocus and willBlur events and only render your page when it is focused.

Example

class MyPage extends React.Component {
  state = {
    isFocused: false
  };

  componentDidMount() {
    this.subs = [
      this.props.navigation.addListener("didFocus", () => {
        this.setState({ isFocused: true })
      }),
      this.props.navigation.addListener("willBlur", () => {
        this.setState({ isFocused: false })
      })
    ];
  }

  componentWillUnmount() {
    this.subs.forEach(sub => sub.remove());
  }

  render() {
    const { isFocused } = this.state;

    if (!isFocused) {
      return null;
    }

    return <MyComponent />;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM