是否可以在 React 的 useEffect 中使用自定义钩子?

IT技术 reactjs react-hooks
2021-05-12 02:28:34

我有一个非常基本的自定义钩子,它接受一个路径并从 firebase 返回一个文档

import React, { useState, useEffect, useContext } from 'react';
import { FirebaseContext } from '../sharedComponents/Firebase';

function useGetDocument(path) {
    const firebase = useContext(FirebaseContext)
    const [document, setDocument] = useState(null)

    useEffect(() => {
        const getDocument = async () => {
            let snapshot = await firebase.db.doc(path).get()
            let document = snapshot.data()
            document.id = snapshot.id
            setDocument(document)
        }
        getDocument()
    }, []);

    return document
}

export default useGetDocument

然后我使用 useEffect 作为 componentDidMount/constructor 来更新状态

useEffect(() => {
    const init = async () => {

      let docSnapshot = await useGetDocument("products/" + products[selectedProduct].id + "labels/list")
      if(docSnapshot) {
        let tempArray = []
        for (const [key, value] of Object.entries(docSnapshot.list)) {
          tempArray.push({id: key, color: value.color, description: value.description})
        }
        setLabels(tempArray)
      } else {
        setLabels([])
      }

      await props.finishLoading()
      await setLoading(false)
    }
    init()
  }, [])

但是,我从“throwInvalidHookError”得到了一个不变违规,这意味着我违反了钩子的规则,所以我的问题是你是否不能在 useEffect 中使用自定义钩子,或者我是否做错了什么。

3个回答

据我所知,组件中的钩子应该始终处于相同的顺序。而且由于useEffect有时会发生,而不是每个渲染都违反了hooks规则在我看来,您useGetDocument并没有真正的需要。

我提出以下解决方案:

  1. 保持你useGetDocument的相同。
  2. 改变你的组件有一个useEffect具有document作为一个依赖。

您的组件可能如下所示:

const Component = (props) => {
    // Your document will either be null (according to your custom hook) or the document once it has fetched the data.
    const document = useGetDocument("products/" + products[selectedProduct].id + "labels/list");

    useEffect(() => {
        if (document && document !== null) {
            // Do your initialization things now that you have the document.
        }
    }, [ document ]);

   return (...)
}

当然你可以在其他钩子中调用钩子。

不要从常规 JavaScript 函数调用 Hook。相反,您可以:

✅ 从 React 函数组件调用 Hook。

✅ 从自定义 Hooks 调用 Hooks(我们将在下一页了解它们)。

但...

您没有在另一个钩子中使用钩子

你意识到你传递给 useEffect 的是一个回调,因此你在回调的主体内使用你的自定义钩子而不是钩子(useEffect)。

如果你碰巧使用 ESLint 和 react-hooks 插件,它会警告你:

ESLint: React Hook "useAttachDocumentToProspectMutation" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.(react-hooks/rules-of-hooks)

话虽如此,您根本不需要 useEffect。并且 useGetDocument 不返回Promise而是返回文档。

调用钩子时

const document = useGetDocument("products/" + products[selectedProduct].id + "labels/list");

它将第一次返回 undefined ,然后根据@ApplePearPerson 的回答呈现后续渲染的文档。

您不能在另一个钩子中使用钩子,因为它违反了规则Call Hooks from React function components并且您传递给的函数useEffect是常规的 javascript 函数。

您可以做的是在另一个自定义钩子中调用一个钩子。

您需要做的是useGetDocument在组件内部调用并将结果传递到useEffect依赖数组中。

let docSnapshot = await useGetDocument("products/" + products[selectedProduct].id + "labels/list")

useEffect(() => { ... }, [docSnapshot])

这样,当docSnapshot更改时,您的useEffect被调用。

其它你可能感兴趣的问题