首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何计算一个变量在一小时/一天内有多少次为真?

如何计算一个变量在一小时/一天内有多少次为真?
EN

Stack Overflow用户
提问于 2022-05-12 15:18:46
回答 2查看 67关注 0票数 0

我正在编写一个运动检测应用程序Reactive原住民,我想计算多少次警报已经在一小时和一天内触发。

我用redux工具包获得警报的状态(真/假)

代码语言:javascript
运行
复制
    const alarmValue = useSelector((state) => state.alarm.active);

并希望输出在文本字段中触发警报的次数,但我不知道如何触发,特别是在一小时或一天内。任何想法都是非常感谢的!

EN

回答 2

Stack Overflow用户

发布于 2022-05-12 16:03:10

代码语言:javascript
运行
复制
    useEffect(() => {
       // This code will run when the alarm value changes and here you can check if it is changed to true

If (alarmValue) {
// Here you can just Crete a new state variable to store the count and increment it 
}
    })
票数 0
EN

Stack Overflow用户

发布于 2022-05-12 16:13:49

希望这会有所帮助,但在React.js中,您可以尝试使用一个数组来保存alarmValue状态的记录,然后使用另一个变量来记录在过去24小时内触发警报的次数:

代码语言:javascript
运行
复制
const [alarmValue, setAlarmValue] = useState(false);    
const [timesTriggered, setTimesTriggered] = useState(0);
let alarmArray = [];

然后需要使用useEffect钩子:

代码语言:javascript
运行
复制
useEffect(() => {
    const appendEveryMinute = setInterval(() => {
        alarmArray.append(alarmValue);
        console.log("This will be called every 60 seconds");
    }, 60000); 
    // alternatively you should be able to do 60 * 1000
    
    const checkTimesTriggered = setInterval(() => {
        for (const alarm of alarmArray) { // for each alarm in the array
            if (alarm) { // if alarm is true
                setTimesTriggered(alarmTriggered + 1); // increment timesTriggered
           }
        }

        console.log("Alarm has been triggered " + timesTriggered + " times");

        setTimesTriggered(0) 
        // we reset timesTriggered so it will recalculate every hour

        console.log("This will be called every hour");
    }, 3600000); // alternatively you should be able to do 3600 * 1000

    return () => {
        clearInterval(appendEveryMinute);
        clearInterval(checkTimesTriggered);
    };
});

也许这会给你一个好的开始。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72218209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档