React Native clearInterval在componentWillUnmount()中不起作用

问题描述 投票:0回答:1

我有一个React Native组件,看起来像这样:

  constructor(props) {
    super(props);

    this.dataRefreshId = null;
  };

  componentDidMount() {
    this.dataRefreshId = setInterval(
      () => ApiMatch.fetchFriendlyQueueInfo(),
      REFRESH_FRIENDLY_QUEUE_DATA_INTERVAL,
    );
  };

  componentWillUnmount() {
    console.log(this.dataRefreshId);  // Is triggered and returns an ID
    clearInterval(this.dataRefreshId);
  };

[不幸的是,当我离开呈现组件的屏幕之后,即使componentWillUnmount被触发,因为其中的conosle.log()返回了实际ID,该间隔中的函数仍继续被调用,就好像该间隔已经消失了一样。没有被清除。我试图将零件移到构造函数内的componentDidMount中,但没有成功。

我想提一提,我不使用任何类型的导航包。

react-native
1个回答
0
投票
ignore componentWillUnmount  use NavigationEvents is much better than componentWillUnmount 

示例

var dataRefreshId =' '

//班级声明前

    <NavigationEvents
              onWillFocus={payload => {
              dataRefreshId =  setInterval(() => {             
              ApiMatch.fetchFriendlyQueueInfo(),
              REFRESH_FRIENDLY_QUEUE_DATA_INTERVAL;
         })
     }
 }
              onWillBlur={                    
                   payload => {
                         clearInterval(dataRefreshId);                        
                     }
       }

/>
© www.soinside.com 2019 - 2024. All rights reserved.