亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我在 React 中收到無效的 Hook 調用?

為什么我在 React 中收到無效的 Hook 調用?

肥皂起泡泡 2021-12-23 10:36:18
這是我的代碼,它給出了Invalid Hook Call錯誤,我無法弄清楚我到底做錯了什么。我如何在不調用函數中的鉤子的情況下實現我在這段代碼中所做的事情?const useTimer = ({ days  =0 , hours = 0 , minutes = 0 , seconds = 10 , millis = 0  } :{days?:number , hours? : number , minutes ?:number , seconds? : number , millis? : number} )=>{  const [time, setTime] = useState({ days , hours , minutes , seconds , millis });  const [started , setStarted] = useState(false) ;   const originalTime = { days , hours , minutes , seconds , millis }  const countDown = ()=>{    setTime(t=>{      let totalMillis  = 1000*(t.days * 24 * 3600 + t.hours * 3600 + t.minutes * 60 + t.seconds ) + t.millis ;       return {        days : totalMillis/(24*3600*1000) ,         hours : totalMillis/(3600*1000) ,         minutes : totalMillis/(60*1000) ,         seconds : totalMillis/1000 ,         millis : totalMillis%1000      }    })    }  const onTimeout = (callback : Function)=>{    callback() ;   }  const reset = ()=>{    setTime({...originalTime}) ;  }  const stop = ()=>{    setStarted(false) ;   }  const start= ()=>{    if(!started) setStarted(true) ;     setInterval(()=>{      if(started) countDown() ;     } , 1 ) ;   }  return {time , start , stop , reset , onTimeout} ; };  這是完整的錯誤消息:Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:1. You might have mismatching versions of React and the renderer (such as React DOM)2. You might be breaking the Rules of Hooks3. You might have more than one copy of React in the same appSee fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.錯誤發生在第二行本身: const [time, setTime] = useState({ days , hours , minutes , seconds , millis });我正在像這樣使用這個鉤子:const App = ()=> {    const { time } = useTimer({ days: 10 });    return (      <div>        <h1>{time}</h1>      </div>    )}為了制作這個庫,我正在使用:create-react-library包。這是我的存儲庫的鏈接:https : //github.com/nateshmbhat/use-timer-react
查看完整描述

2 回答

?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

您的代碼中存在一些錯誤,因此我進行了一些修復。以下是工作版本。如果您需要任何解釋,請告訴我。


const { useState, useRef } = React;

function App() {

  const { time, start, stop, reset, onTimeout } = useTimer({

    days: 10,

    interval: 100,

  });

  start();

  return (

    <div>

      <h1>{JSON.stringify(time, undefined, 2)}</h1>

    </div>

  );

}


const useTimer = ({

  days = 0,

  hours = 0,

  minutes = 0,

  seconds = 10,

  millis = 0,

  interval = 1000,

}) => {

  const [time, setTime] = useState({

    days,

    hours,

    minutes,

    seconds,

    millis,

  });

  const started = useRef(false);

  const originalTime = {

    days,

    hours,

    minutes,

    seconds,

    millis,

  };


  const countDown = () => {

    setTime(t => {

      let totalMillis =

        1000 *

          (t.days * 24 * 3600 +

            t.hours * 3600 +

            t.minutes * 60 +

            t.seconds) +

        t.millis -

        interval;

      return {

        days: Math.floor(totalMillis / 86400000),

        hours: Math.floor(

          (totalMillis % 86400000) / 3600000

        ),

        minutes: Math.floor(

          (totalMillis % 3600000) / 60000

        ),

        seconds: Math.floor((totalMillis % 60000) / 1000),

        millis: totalMillis % 1000,

      };

    });

  };


  const onTimeout = callback => {

    callback();

  };


  const reset = () => {

    setTime({ ...originalTime });

  };


  const stop = () => {

    start.current = false;

  };


  const start = () => {

    if (!started.current) {

      started.current = true;

      setInterval(() => {

        if (started.current) countDown();

      }, interval);

    }

  };


  return { time, start, stop, reset, onTimeout };

};


ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>


查看完整回答
反對 回復 2021-12-23
?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

問題是:您在嵌套函數中調用了 react hook,這違反了react hooks規則。

我可以看到您正在嘗試使用 react 函數中其他函數中的 usestate 掛鉤來設置狀態。你可能想重新思考你的邏輯


查看完整回答
反對 回復 2021-12-23
  • 2 回答
  • 0 關注
  • 336 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號