简体   繁体   English

在自定义钩子中使用 nextjs 进行无效的钩子调用

[英]invalid hook call with nextjs inside custom hook

I'm getting a invalid hook call error when using state inside my custom hook.在我的自定义挂钩中使用 state 时出现无效的挂钩调用错误。 Here's my code这是我的代码

import { useState } from 'react';

export default function useFetch() {
  const [randomValue, setRandomValue] = useState<number>();
  setRandomValue(3);

  return randomValue;
}

the hook is inside my hooks folder on the path: ./src/hooks钩子在路径上的我的钩子文件夹中:./src/hooks

any reason for that?有什么理由吗?

Your comment mentions you call useFetch() from inside useEffect() .您的评论提到您从 useEffect() 内部调用useFetch() useEffect() That's where your problem is.这就是你的问题所在。

Hooks are only valid when called during render of a component.挂钩仅在组件渲染期间调用时有效。 useEffect() is triggered after a render. useEffect()在渲染后触发。 So you cannot call any hook from inside useEffect .所以你不能从useEffect内部调用任何钩子。

It's hard to advise how to fix that since you haven't posted that code.由于您尚未发布该代码,因此很难建议如何解决该问题。


Also, and this is equally important, never call a state setter function during render.此外,这同样重要,切勿在渲染期间调用 state 设置器 function。 And remember that hook functions run when the component renders.请记住,钩子函数在组件呈现时运行。 Setting state triggers a render, so this typically results in an infinite loop.设置 state 会触发渲染,因此这通常会导致无限循环。

Most of time when fetching a value and setting it in state, you should have a valid initial value for its type (like null ), and a useEffect() to set something you want.大多数时候,当获取一个值并将其设置在 state 中时,您应该为其类型(如null )设置一个有效的初始值,并使用useEffect()来设置您想要的东西。

Remember that useEffect means "use side effect" where a side effect is something that a render may trigger, but is not executed synchronously every single render.请记住, useEffect表示“使用副作用”,其中副作用是渲染可能触发的东西,但不会在每个渲染中同步执行。

export default function useFetch() {
  const [randomValue, setRandomValue] = useState<number | null>(null);

  useEffect(() => {
    setRandomValue(Math.floor(Math.random() * 10));
  }, [setRandomValue]}


  return randomValue;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM