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

时间:2020-06-05 14:43:49

标签: react-native

编辑:请忽略该问题。我在另一个导致它的代码文件中发现了一个令人难以置信的愚蠢: this['window'].clearInterval = function() {};

我有一个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中,但没有成功。

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

编辑:请忽略该问题。我在另一个导致它的代码文件中发现了一个令人难以置信的愚蠢: this['window'].clearInterval = function() {};

1 个答案:

答案 0 :(得分: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);                        
                     }
       }

/>

https://reactnavigation.org/docs/4.x/navigation-events/