javascript - 为什么我在 React 中收到无效的 Hook 调用?

标签 javascript reactjs react-hooks

这是我的代码,它给出了 Invalid Hook Call 错误,我无法弄清楚我到底做错了什么。我如何在不调用函数内的 Hook 的情况下实现我在这段代码中所做的事情?

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 Hooks
3. You might have more than one copy of React in the same app
See 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 });

我是这样使用这个钩子(Hook)的:

const App = ()=> {

    const { time } = useTimer({ days: 10 });
    return (
      <div>
        <h1>{time}</h1>
      </div>
    )

}

为了制作这个库,我正在使用:create-react-library 包。这是我的存储库的链接:https://github.com/nateshmbhat/use-timer-react

最佳答案

您的代码中存在一些错误,因此我进行了一些修复。以下是工作版本。如果您需要任何解释,请告诉我。

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>

关于javascript - 为什么我在 React 中收到无效的 Hook 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791698/

相关文章:

javascript - 在 ReactJs 中使用 Javascript 进行类操作

javascript - react 函数中的类激活

javascript - react Hook : old state value persisting in closure

javascript - 在 React JS 的回调中使用自定义钩子(Hook)

javascript - 在 Promise.all 中 react setState

javascript - 创建自定义 JS 语法/速记

javascript - 使用 Jquery 克隆 Select2

css - Material UI Chips - 阻止它们在事件时改变颜色

javascript - 如何使用两个预定义值绑定(bind) HTML 中的选择选项以在 mongodb 中插入数据

javascript - javascript bing map 中的可拖动和可点击图钉