reactjs - 是否可以在 React 的 useEffect 中使用自定义钩子(Hook)?

标签 reactjs react-hooks

我有一个非常基本的自定义 Hook ,它接受路径并从 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/构造函数来更新状态

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”中得到了不变违规,这意味着我违反了钩子(Hook)规则,所以我的问题是你是否不能在 useEffect 中使用自定义钩子(Hook),或者我是否做了其他错误的事情。

最佳答案

据我所知,组件中的钩子(Hook)应该始终保持相同的顺序。而且由于 useEffect 有时会发生,而且并不是每个渲染都会破坏 rules of hooks 。在我看来,您的 useGetDocument 没有真正的需要。

我提出以下解决方案:

  1. 保持 useGetDocument 不变。
  2. 更改您的组件,使其具有将 document 作为依赖项的 useEffect

您的组件可能如下所示:

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

关于reactjs - 是否可以在 React 的 useEffect 中使用自定义钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59070930/

相关文章:

javascript - react : Re-render parent component based on Child component

javascript - react 页面未呈现所有元素且没有标题

html - React useState() 不会同步更新值

javascript - 为什么 React Hook useState 使用 const 而不是 let

javascript - Reactjs:使用 .blur() 取消聚焦按钮元素

reactjs - .d.ts 文件的范围是什么

javascript - 如何在 React 16 中使用 ReactDOM.createPortal() ?

javascript - 如何在 promise 中设置 react 钩子(Hook)的值(value)?

javascript - 为什么当我尝试使用 React Native Hooks 时,它不能按预期正常工作?

reactjs - 如何在不重复触发的情况下更新 useEffect 中的卸载处理程序?