我希望“百分比”在按下“開始”按鈕后每秒減少 0.25。
但“百分比”輸出為“物件物件”。
import React, {useState, useRef, useCallback} from 'react';
const App = () => {
const [percent,setPercent] = useState(1);
const intervalRef = useRef(null);
const start = useCallback(() =>{
if (intervalRef.current !== null){
return;
}
intervalRef.current = setInterval(()=>{
if (percent > 0){
setPercent(c => c - 0.25);
console.log("percent = " {percent});
}
else {
setPercent(c => 1);
}
}, 1000);
}, []);
return (
<div>
<button onClick={()=>{start()}} />
</div>
);
}
uj5u.com熱心網友回復:
你的問題僅僅是它列印'object Object'的事實嗎,這是因為你 在字串和物件之間使用運算子,這會將物件轉換為字串,從而生成字串'object Object'。
要以您想要的方式列印物件,您應該使用 但將其作為第二個引數傳遞給console.log
console.log("percent = ", { percent });
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445040.html
