首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何删除react导航的事件侦听器?

如何删除react导航的事件侦听器?
EN

Stack Overflow用户
提问于 2022-07-26 16:54:46
回答 2查看 1.4K关注 0票数 3

我想检测到在Reactive原住民中导航的焦点变化。我正在使用类组件,但是现在RN社区充斥着功能组件。

以下是@的片段

代码语言:javascript
复制
function Profile({ navigation }) {
    React.useEffect(() => {
      const unsubscribe = navigation.addListener('focus', () => {
        // Screen was focused
        // Do something
      });
  
      return unsubscribe;
    }, [navigation]);
  
    return (
        <>
            <Text>tedtx</Text>
        </>
    );
  }

我在类组件中使用过,它运行良好,还没有内存泄漏警告,但我不知道这是否是一种方法。

代码语言:javascript
复制
    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
   }

我注意到重新加载地铁会移除侦听器。当我保存文件(热重加载)并尝试调用焦点上的侦听器时,它实际上增加了。我每次热装的时候都会增加一个。似乎听众并没有被移除。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-26 17:22:18

你可以试试这个

代码语言:javascript
复制
class Profile extends React.Component {
  componentDidMount() {
    this._unsubscribe = navigation.addListener('focus', () => {
      // do something
    });
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

  render() {
    // Content of the component
  }
}

响应导航事件:https://reactnavigation.org/docs/navigation-events/

票数 4
EN

Stack Overflow用户

发布于 2022-07-26 17:24:37

代码语言:javascript
复制
componentDidMount(){
  this.focusListener = this.props.navigation.addListener('focus',() => {
    log('route ',this.props);
  });
  // should I return here
  // nothing to return
}

componentWillUnmount() {
  this.focusListener();
}

是的,大多数示例都显示了函数组件中的用法,但是在文档中有一个示例显示了如何在类组件中设置/删除导航侦听器。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73127136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档