admin管理员组文章数量:1336215
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 02 Answers
Reset to default 4use 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 />;
}
}
本文标签: javascriptReactNavigation Call function whenever page is navigated toStack Overflow
版权声明:本文标题:javascript - React-Navigation: Call function whenever page is navigated to - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742340371a2456480.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论