javascript - React Native setInterval 函数适用于具有不同持续时间的多个函数

标签 javascript reactjs react-native

我在 React Native 组件中有两个函数,一个函数应该每 10 秒刷新一次,另一个函数应该每 1 秒刷新一次。我已经实现了 setInterval() 刷新 componentDidMount() 功能和 clearInterval() componentWillUnmount() ,但我遇到了麻烦,它只需要一个持续时间最短的函数。但如果设置两个函数的持续时间相同,我就能得到结果。

这是示例

...
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      btLevel: 0,
      btState: null,
    };
  }
  componentDidMount() {
    this.getBtLevels();
    this.getBtState();
    this.batLS2();
    this.batLS10();
  }
  componentWillUnmount() {
    clearInterval(() => { this.batLSS(); this.batLS10(); });
  }
  getBtLevels = () => {
    fetch(apiUrl).then((res) =>
      this.setState({btLevel: res.level}),
    );
  };
   getBtLevelArcs = () => {
      fetch(apiUrl).then((res) =>
      this.setState({btLevelArc: res.level}),
    );
   };

  getBtState = () => {
     fetch(apiUrl).then((res) =>
      this.setState({BtState: res.state}),
    );
  };
  
   batLS10 = () => {
     setInterval(() => {
      this.getBtLevelArcs();
  
    }, 10000);
   };
  batLS2 = () => {
    setInterval(() => {
       this.getBtLevels();
       this.getBtState();
    }, 1000);
  };

...

关于上面的代码this.getBtLevels(); this.getBtState();每 1 秒获取一次值和 this.getBtLevelArcs();每 10 秒获取一次值。在此this.getBtLevels(); this.getBtLevelArcs();函数获得相同的值。但一个应该每 1 秒刷新一次,另一个应该每 10 秒刷新一次。这里得到的是 1s setInterval 函数 this.batLS2()正在刷新整个组件。

我怎样才能实现这个应该刷新值 1 秒和另一个 10 秒。

这里是原始版本代码。 Expo

最佳答案

问题

clearInterval 通过传递从 setInterval 返回的引用来工作,即 this.timerId = setInterval(...clearInterval (this.timerId)

我怀疑正在发生的事情是您编辑了代码并运行,这设置了一个间隔回调(但没有清除它),然后编辑并重新运行您的代码,这设置了另一个间隔回调(同样,没有清除) )等...当组件卸载时(如页面刷新),您基本上不会清理间隔回调。

解决方案

为每个间隔计时器添加一个计时器变量

constructor(props) {
  super(props);
  
  ...

  this.timer1 = null;
  this.timer2 = null;
}

卸载时清除每个间隔

componentWillUnmount() {
  clearInterval(this.timer1)
  clearInterval(this.timer2)
}

保存计时器引用

batLS10 = () => {
  this.timer2 = setInterval(() => {
    this.getBtLevelArcs();
  }, 10000);
};

batLS2 = () => {
  this.timer1 = setInterval(() => {
    this.getBtLevels();
    this.getBtState();
  }, 1000);
};

Edit nostalgic-snow-iqx3u

关于javascript - React Native setInterval 函数适用于具有不同持续时间的多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63185883/

相关文章:

php - 当 SPA 中的路由发生变化时,http 请求会发生什么情况

javascript - 如何修复 "... is not a function"错误?

android - 如何在我的 React Native 应用程序中显示 gif?

javascript - Jquery日期选择器: Select one date,自动更新第二个字段

javascript - Grunt 连接服务器返回无法通过主干网获取/路由

reactjs - 索引签名是解决我的 React props TypeScript 接口(interface)问题的正确方法吗?

设置 Firebase+Crashlytics 时 Android 项目构建失败

android - ZipException : duplicate entry: com/google/android/gms/internal/measurement/zzwn. 类

javascript - 将 jQuery end() 函数与破坏性方法一起使用

javascript - 为什么我的复选框不能通过 id 来检查