我正在编写一个运动检测应用程序Reactive原住民,我想计算多少次警报已经在一小时和一天内触发。
我用redux工具包获得警报的状态(真/假)
    const alarmValue = useSelector((state) => state.alarm.active);并希望输出在文本字段中触发警报的次数,但我不知道如何触发,特别是在一小时或一天内。任何想法都是非常感谢的!
发布于 2022-05-12 16:03:10
    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 
}
    })发布于 2022-05-12 16:13:49
希望这会有所帮助,但在React.js中,您可以尝试使用一个数组来保存alarmValue状态的记录,然后使用另一个变量来记录在过去24小时内触发警报的次数:
const [alarmValue, setAlarmValue] = useState(false);    
const [timesTriggered, setTimesTriggered] = useState(0);
let alarmArray = [];然后需要使用useEffect钩子:
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);
    };
});也许这会给你一个好的开始。
https://stackoverflow.com/questions/72218209
复制相似问题