useState 未更新
P粉245003607
P粉245003607 2023-09-14 21:42:54
0
2
486

你能告訴我為什麼我的 useState 仍然是空的嗎?它不想更新它。我正在使用 setInteraval 和函數來更新數據,並且希望在當前時間設定 useState,但 useState 忽略 formatTime 中的 setTimeOut(res) 。 你能告訴我如何修復它嗎?

編輯:如果我將數字放入 useState

#
const [timeOut, setTimeOut] = useState(30)

它會在第二秒出現,然後就消失了,我有空的字段。 好像setInterval刪除了裡面的所有內容,那麼要如何修復呢?

const Timer = ({item}) => {

  const [timeOut, setTimeOut] = useState('')  // << doent want to update it from 
                                              //         formatTime function
  console.log(timeOut) // still empty


useEffect(() => {
    if (status !== 'unPaid') return;

    const timer = window.setInterval(() => {
        setTimeOut(formatTime(createdAt));
    }, 1000);

    return () => window.clearInterval(timer);
}, [createdAt, status]);



const formatTime = (time) => {
         console.log(time) //  2023-07-25T23:39:39.253Z

         // const timer = new Date(time).getTime() + 1800000
          const timer = new Date(time).getTime() + 250000
          let countDown = new Date().getTime()
          let distance = timer - countDown

          let min = Math.floor((distance % (1000*60*60) / (1000*60)))
          let sec = Math.floor((distance % (1000*60) / (1000)))
          let res = Math.abs(min) + ':' + Math.abs(sec)
          console.log(res)   //  4:50
          setTimeOut(res)   // <<<<<   it doesnt want to apdate my useState
           
 }

P粉245003607
P粉245003607

全部回覆(2)
P粉103739566

這很可能是因為您在超時內設定狀態。

另一個問題是您在其內部呼叫 setTimeout。

相反,使用一個根據先前狀態傳回新值的函數。

useState 接受一個函數,該函數接收 previousState 作為參數

const [count, setCount] = useState(0);

useEffect(() => {
  window.setTimeout(() => {
    setCount((prevValue) => {
      return prevValue + 1; // what you return here, will be the new state.
    })
  }, 1000)
}, []);
P粉990008428

看起來問題是 setInterval 每秒運行一次,並且每秒更新狀態(timeOut)。

此外,在formatTime函數中,您使用的是當前時間(new Date().getTime())而不是createdAt時間。因此,狀態每秒不斷更新為新值。

這是更新後的程式碼。

const Timer = ({ item }) => {
  const [timeOut, setTimeOut] = useState('');

  useEffect(() => {
    if (status !== 'unPaid') return;

    const timer = window.setInterval(() => {
      setTimeOut(formatTime(createdAt));
    }, 1000);

    return () => window.clearInterval(timer);
  }, [createdAt, status]);

  const formatTime = (time) => {
    const timer = new Date(time).getTime() + 250000;
    const currentTime = new Date().getTime();
    const distance = timer - currentTime;

    let min = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    let sec = Math.floor((distance % (1000 * 60)) / 1000);
    let res = Math.abs(min) + ':' + Math.abs(sec).toString().padStart(2, '0');
    return res;
  };

  return <div>{timeOut}</div>;
};
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!