我想检测到在Reactive原住民中导航的焦点变化。我正在使用类组件,但是现在RN社区充斥着功能组件。
以下是@的片段
function Profile({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// Screen was focused
// Do something
});
return unsubscribe;
}, [navigation]);
return (
<>
<Text>tedtx</Text>
</>
);
}我在类组件中使用过,它运行良好,还没有内存泄漏警告,但我不知道这是否是一种方法。
componentDidMount(){
this.state.focusListener = this.props.nav.navigation.addListener('focus',()=>{
log('route ',this.props)
})
// should I return here
}
componentWillUnmount(){
// or should i something here?
// this.props.nav.navigation.removeListener(this.state.focusEvent)
//above does not give error but not removing listener
}我注意到重新加载地铁会移除侦听器。当我保存文件(热重加载)并尝试调用焦点上的侦听器时,它实际上增加了。我每次热装的时候都会增加一个。似乎听众并没有被移除。
发布于 2022-07-26 17:22:18
你可以试试这个
class Profile extends React.Component {
componentDidMount() {
this._unsubscribe = navigation.addListener('focus', () => {
// do something
});
}
componentWillUnmount() {
this._unsubscribe();
}
render() {
// Content of the component
}
}发布于 2022-07-26 17:24:37
componentDidMount(){
this.focusListener = this.props.navigation.addListener('focus',() => {
log('route ',this.props);
});
// should I return here
// nothing to return
}
componentWillUnmount() {
this.focusListener();
}是的,大多数示例都显示了函数组件中的用法,但是在文档中有一个示例显示了如何在类组件中设置/删除导航侦听器。
https://stackoverflow.com/questions/73127136
复制相似问题