为什么我在React中收到无效的Hook呼叫?

问题描述 投票:0回答:1

这是我的代码出现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 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 });

我正在像这样使用这个钩子:

class App extends Component {
  render() {
    const { time } = useTimer({ days: 10 });
    return (
      <div>
        <h1>{time}</h1>
      </div>
    )
  }
}
javascript reactjs react-hooks
1个回答
0
投票

问题是:您正在嵌套函数中调用反应挂钩,这是针对rule of react hooks的。

我可以看到您正在尝试使用react函数中其他函数中的usestate挂钩来设置状态。您可能需要重新考虑自己的逻辑

© www.soinside.com 2019 - 2024. All rights reserved.