【问题标题】:React - Error: Rendered more hooks than during the previous render with Custom HookReact - 错误:渲染的钩子比使用自定义钩子的先前渲染期间更多
【发布时间】:2021-01-31 19:22:58
【问题描述】:

我有一个组件,我在其中调用我的自定义钩子。

自定义挂钩如下所示:

import { useQuery } from 'react-apollo';

export function useSubscription() {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  if (loading) return false
  if (error) return null

  return data
}

然后我正在使用它导致错误的组件是:

export default function Form(props) {
  const router = useRouter();

  let theSub = useSubscription();
  if (theSub === false) {
    return (
      <Spinner />
    )
  } // else I'll have the data after this point so can use it.

  useEffect(() => {

    if (!isDeleted && Object.keys(router.query).length !== 0 && router.query.constructor === Object) {
      setNewForm(false);

      const fetchData = async () => {
        // Axios to fetch data
      };

      fetchData();
    }

  }, [router.query]);

  // Form Base States
  const [newForm, setNewForm] = useState(true);
  const [activeToast, setActiveToast] = useState(false);


  // Form Change Methods
  const handleUrlChange = useCallback((value) => setUrl(value), []);

  const handleSubmit = useCallback(async (_event) => {
    // Submit Form Code
  }, [url, selectedDuration, included, excluded]);


  return (
    <Frame>
      My FORM
    </Frame>

  )


}

有什么想法吗?

【问题讨论】:

  • 你是否有条件地调用任何钩子?
  • 不 - 没有条件
  • 可以分享Form组件的完整代码吗?
  • @Yousaf - 我已经用表单组件代码更新了帖子
  • 尝试将if (theSub === false) {移动到return (...)之前。

标签: reactjs react-hooks


【解决方案1】:

第一次渲染组件时可以使用useEffect调用hook。

export default function Form(props) {
  const router = useRouter();
  const [theSub, setTheSub] = useState(null);
  useEffect(() => { setTheSub(useSubscription()); }, []);
  
  if (theSub === false) {
    return (
      <Spinner />
    )
  } // else I'll have the data after this point so can use it.

  // I have some other states being set and used related to the form e.g:
  // const [whole, setWhole] = useState(true);

  return (... The form ...)

【讨论】:

  • 在useeffect里面不能调用hook!
  • 是的 - 不能在里面 else get Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
  • 感谢您告诉我。那么,是什么阻止您在 Form 组件中调用该钩子呢?我的意思是,你可以在 Form 组件中使用 useQuery。
猜你喜欢
  • 2020-06-20
  • 2021-11-02
  • 1970-01-01
  • 2021-04-26
  • 2022-08-03
  • 2021-09-29
  • 2023-02-13
  • 2021-10-12
  • 2021-02-09
相关资源
最近更新 更多