我想要一些帮助,了解为什么我的反应组件不工作。我正在尝试通过制作一个基本的计时器来完成我的React/Js基本原理。组件是呈现很棒,只是什么都没有发生。我正在查看Chrome上的,我的变量似乎正在正确地更新。
我知道这是基本的,我宁愿开始改正我的错误,在路上学习。
任何帮助都将不胜感激!
import React from 'react'
var sec = 0;
var min = 0;
var hrs = 0;
var timer_id;
// Helper Functions
function tick(){
sec++;
if (sec >= 60){
sec = 0;
min ++;
if (min >= 60){
min = 0;
hrs++;
};
};
}
function add(){
tick();
timer();
}
function timer(){
console.log("TIMER");
timer_id = setTimeout(add, 1000);
}
// Clock Component
class Clock extends React.Component{
render(){
timer();
return (
<div className="clock-face">
<h4> {hrs} : {min} : {sec}</h4>
<button
onClick = {() => clearTimeout(timer_id)}> Stop </button>
</div>
);
}
}
export default Clock;发布于 2021-08-02 19:05:29
只有当组件的道具或状态发生更改时(或被迫更改,但我们不这样做),get组件才会被重新命名。您正在更新全局变量中的小时/分钟/秒;这些变量不是由React跟踪的。
此外,让render()执行一个副作用(在您的情况下是timer())并不是一个好主意;function可能不止一次地呈现您的功能。
下面是一个例子,您的时钟是一个类组件,它会在计时器卸载后滴答作响并清除定时器。
在这里导致重命名的神奇之处是调用this.setState。
import React from "react";
function divmod(a, b) {
return [Math.floor(a / b), a % b];
}
class Clock extends React.Component {
state = { time: 0 };
componentDidMount() {
this.timer = setInterval(this.tick, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
tick = () => {
this.setState(({ time }) => ({ time: time + 1 }));
};
render() {
const { time } = this.state;
const [hmins, secs] = divmod(time, 60);
const [hrs, mins] = divmod(hmins, 60);
return (
<div className="clock-face">
<h4>
{" "}
{hrs} : {mins} : {secs}
</h4>
</div>
);
}
}https://stackoverflow.com/questions/68626755
复制相似问题