我正在嘗試使用 REACT 中的類組件來完成這個倒數計時器。我相信我只是缺少“this.Setstate”添加 . 您能否查看并讓我知道將在此組件中添加的位置?提前致謝!(我已經通過添加“this.Setstate”來編輯代碼,但是,我收到一條錯誤訊息,指出它不是函式)。只是為了添加更多細節,我試圖在螢屏加載時啟動倒數計時器。它不是由按鈕或任何東西觸發的。
import React,{Component} from "react";
class Countdown extends Component{
constructor(props){
super(props);
this.state={
days:30,
hours:720,
minutes:59,
seconds:59
}
}
componentDidMount(){
let countDownDate = new Date("Jul 30, 2022 11:00:00").getTime();
/*Function myFunc runs every second*/
let myfunc = setInterval(function() {
let now = new Date().getTime();
let timeleft = countDownDate - now;
this.setState({
days: Math.floor(timeleft / (1000 * 60 * 60 * 24)),
hours : Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes: Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((timeleft % (1000 * 60)) / 1000),
})
} , 1000);
}
render(){
return (
<>
<div>
<p>{this.days}</p>
<p>{this.hours}</p>
<p>{this.minutes}</p>
<p>{this.seconds}</p>
</div>
</>
)
}
}
export default Countdown;
uj5u.com熱心網友回復:
如您所述,要將值保存在狀態中,您實際上需要添加該this.setState方法。
您當前正在將日期值存盤到全域值中,例如this.days. 這有效,但它不會在更改時重新渲染組件。
所以你需要做的是用這樣的this.<DATE_VALUE>東西替換:
/*Breakdown the calculation*/
this.setState({
days: YOUR_DAYS_VALUES,
hours: YOUR_HOURS_VALUES,
minutes: YOUR_MINUTES_VALUES,
seconds: YOUR_SECONDS_VALUES,
})
編輯:
正如@madQuestions 評論的那樣,在函式this.setState內部,setInterval我們需要將其系結到當前類(箭頭函式不需要這樣做)。發生這種情況是因為在setInterval范圍內我們沒有類值的線索。這就是為什么我們需要系結。
您可以查看此評論帖子以更好地了解正在發生的事情。
所以你的間隔看起來像這樣:
let myfunc = setInterval(
function () {
let now = new Date().getTime();
let timeleft = countDownDate - now;
this.setState({
days: Math.floor(timeleft / (1000 * 60 * 60 * 24)),
hours: Math.floor(
(timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
),
minutes: Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((timeleft % (1000 * 60)) / 1000)
});
}.bind(this), // we added the binding here
1000
);
此外,我能夠在您的代碼中看到您仍在this.<DATE_VALUE>JSX 代碼中回傳。您必須將其更改this.state.<DATE_VALUE>為獲取狀態值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498113.html
上一篇:Symfony6php8物體表單
下一篇:三菱M70宏變數讀取三菱M80公共變數采集三菱CNC變數讀取采集三菱CNC遠程刀補三菱機床在線刀補三菱數控在線測量
