【发布时间】:2018-07-15 17:14:09
【问题描述】:
我正在使用 React-Navigation 开发 React-Native 应用程序,并且我正在使用堆栈导航器。
如何在页面被导航到时调用函数,包括在 goBack() 事件中?如果我将方法放在构造函数中,它只会在其初始创建时触发,而不是在通过 goBack() 获得时触发。
【问题讨论】:
标签: javascript reactjs react-native react-navigation
我正在使用 React-Navigation 开发 React-Native 应用程序,并且我正在使用堆栈导航器。
如何在页面被导航到时调用函数,包括在 goBack() 事件中?如果我将方法放在构造函数中,它只会在其初始创建时触发,而不是在通过 goBack() 获得时触发。
【问题讨论】:
标签: javascript reactjs react-native react-navigation
使用导航事件 我相信你可以使用做焦点并且会模糊
<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
编辑 2021
import { useIsFocused } from '@react-navigation/native';
const isFocused = useIsFocused();
React.useEffect(()=>{
if(isFocused){
// callback
}
},[isFocused])
【讨论】:
正如您所指出的,组件在更改页面时永远不会卸载,因此您不能依赖构造函数甚至componentDidMount。关于这个话题有很多讨论in this issue。
你可以例如监听 didFocus 和 willBlur 事件,并且仅在页面获得焦点时才呈现您的页面。
示例
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 />;
}
}
【讨论】: