是否可以在 React 的 useEffect 中使用自定义钩子? [英] Is it possible to use a custom hook inside useEffect in React?

查看:18
本文介绍了是否可以在 React 的 useEffect 中使用自定义钩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very basic custom hook that takes in a path an returns a document from 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来更新状态

Then I use useEffect as a componentDidMount/constructor to update the state

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 中使用自定义钩子,或者我做错了什么.

However, I get an Invariant Violation from "throwInvalidHookError" which means that I am breaking the rules of hooks, so my question is whether you can't use custom hooks inside useEffect, or if I am doing something else wrong.

推荐答案

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

As far as I know, the hooks in a component should always be in the same order. And since the useEffect happens sometimes and not every render that does break the rules of hooks. It looks to me like your useGetDocument has no real need.

我提出以下解决方案:

  1. 保持您的 useGetDocument 相同.
  2. 将您的组件更改为具有将 document 作为依赖项的 useEffect.
  1. Keep your useGetDocument the same.
  2. Change your component to have a useEffect that has the document as a dependency.

您的组件可能如下所示:

Your component could look like the following:

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 (...)
}

这篇关于是否可以在 React 的 useEffect 中使用自定义钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆