[英]Getting empty state after calling the handleSubmit event from setInterval function
const QuizPage = () => {
const [allanswers,setToAllAnswer] = useState([]) // have all answers
const startTimer = (tim) => {
const tims = tim * 60 * 1000;
const countdowntime = new Date().getTime() + tims; // time for test
var x = setInterval(() => {
const now = new Date().getTime();
const distance = countdowntime - now;
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (distance < 0) {
clearInterval(x);
handleSubmit(); // this is returning empty state
} else {
setTimerHours(hours);
setTimerMinutes(minutes);
setTimerSeconds(seconds);
}
},1000);
};
const handleStart = () => { // test start
let tim = 1; // test time in minutes
startTimer(tim);
};
const handleSubmit = () => { // on test end
console.log(allanswers);
};
如果此 handleSubmit 由 onClick() 事件調用,它會顯示包含答案的列表。
注意:所有必需的狀態都已在原始代碼中定義。
嗨,我想您忘了調用setToAllAnswer function,這就是 state 為空的原因。
這是運行示例
import React, { useEffect, useState, useRef } from "react";
const HomePage = () => {
const [allanswers, setToAllAnswer] = useState([]) // have all answers
const startTimer = (tim) => {
console.log("start timer");
const tims = tim * 1 * 1000;
const countdowntime = new Date().getTime() + tims; // time for test
var x = setInterval(() => {
console.log("enter in interval");
const now = new Date().getTime();
const distance = countdowntime - now;
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
console.log("distance=======", distance);
if (distance < 0) {
clearInterval(x);
handleSubmit(); // this is returning empty state
} else {
// setTimerHours(hours);
// setTimerMinutes(minutes);
// setTimerSeconds(seconds);
}
}, 1000);
};
const handleStart = () => { // test start
let tim = 1; // test time in minutes
startTimer(tim);
};
const handleSubmit = () => { // on test end
console.log(allanswers);
};
const setAnswer = () => {
setToAllAnswer(["a"]);
}
return (
<div>
<button onClick={handleStart}>start</button>
<button onClick={setAnswer}>set answer</button>
</div>
)
}
export default HomePage;
使用useRef
,您可以確保始終參考最新的 state object。
const [allAnswers, setAllAnswers] = useState([]);
const stateRef = useRef();
stateRef.current = allAnswers;
const handleSubmit = () => { console.log(stateRef.current) };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.