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