最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React-Navigation: Call function whenever page is navigated to - Stack Overflow

programmeradmin1浏览0评论

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().

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().

Share Improve this question edited Jul 15, 2018 at 17:25 Tholle 113k22 gold badges208 silver badges197 bronze badges asked Jul 15, 2018 at 17:14 Adam ArcaroAdam Arcaro 4711 gold badge8 silver badges20 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

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/docs/en/navigation-events.html

EDIT 2022

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

const isFocused = useIsFocused();

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

   // callback
 }
},[isFocused])

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

You could e.g. 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
  };

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

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

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

    if (!isFocused) {
      return null;
    }

    return <MyComponent />;
  }
}
发布评论

评论列表(0)

  1. 暂无评论