javascript - 如何在 react-native 中准确使用和更新全局变量?
问题描述
我是反应原生的新手。我写了秒表,但问题是当我转到另一个页面然后再次返回时,秒表停止工作。我希望秒表一直工作,直到用户按下停止按钮。我知道,我应该使用全局变量,但我不知道如何使用它。这是我的代码:
export default class Record extends Component {
constructor(props) {
super(props);
this.state = {
stopwatchStart: false,
stopWatchTime: '00:00:00'
};
toggleStopwatch() {
if (!this.state.stopwatchStart) {
startDate = new Date();
startTime = startDate.getTime();
that = this;
setInterval(function () {
var date = new Date();
time = (date.getTime() - startTime) / 1000;
hour = parseInt(time / 3600);
timeAgo = parseInt(time % 3600);
min = parseInt(timeAgo / 60);
second = parseInt(timeAgo % 60);
that.setState({
stopWatchTime: (hour + ':' + min + ':' + second)
})
}, 1000);
}
this.setState({ stopwatchStart: !this.state.stopwatchStart });}
解决方案
我认为你应该使用 redux 来处理这个...... https://redux.js.org/
推荐阅读
- reactjs - React Native 和 React 中的 TS 消息
- python - 在 PyTorch 中创建具有不同维度数组的张量
- vue.js - 从 vue/quasar 中的输入字段导出数据
- c# - 未在引发异常的 C# Async 方法中写入的日志
- git - 如何在遥控器消失的地方同步两个存储库
- javascript - 在已安装的 PWA 中丢失指针移动事件
- javascript - 如何从具有额外属性的两个数组创建对象数组?
- php - 查找长度为 8 到 10 的单词,以 S 开头
- sharepoint - 使用 PowerAutomate 将邮件附件保存到共享点会损坏文件
- javascript - 如何在 node.js 中禁用或更新特定网站