[英]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.我正在使用 React-Navigation 开发 React-Native 应用程序,并且我正在使用堆栈导航器。
How can I call a function whenever a page is navigated to, including on goBack() events?导航到页面时如何调用函数,包括 goBack() 事件? If I place the method in my constructor, it is only triggered on its initial creation, and not when it is attained through goBack().
如果我将方法放在我的构造函数中,它只会在其初始创建时触发,而不会在通过 goBack() 获得时触发。
use Navigation Events I believe you can use did focus and will blur使用导航事件我相信你可以使用 did focus 并且会模糊
<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 https://reactnavigation.org/docs/en/navigation-events.html
EDIT 2021编辑 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
.正如您所指出的,在更改页面时永远不会卸载组件,因此您不能依赖构造函数甚至
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.例如,您可以收听
didFocus
和willBlur
事件,并且仅在页面获得焦点时才呈现您的页面。
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 />;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.