programing

useEffect in React에서 커스텀 훅을 사용할 수 있습니까?

fastcode 2023. 3. 31. 22:52
반응형

useEffect in React에서 커스텀 훅을 사용할 수 있습니까?

매우 기본적인 커스텀 훅을 사용하고 있으며, 이 훅은 파이어베이스에서 문서를 반환한다.

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()
  }, [])

단, "throw Invalid"에서 불변 위반을 받습니다.HookError'는 후크의 규칙을 어기고 있다는 것을 의미하기 때문에 useEffect 내에서 커스텀 후크를 사용할 수 없는지, 아니면 제가 다른 일을 하고 있는지 궁금해요.

제가 알기로는 컴포넌트의 훅은 항상 같은 순서로 되어 있어야 합니다.그리고 그 이후로useEffect규칙을 위반하는 모든 렌더링이 아니라 가끔 발생합니다.내가 보기엔 네 것 같아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 (...)
}

다른 후크 안에 있는 후크는 규칙을 위반하므로 사용할 수 없습니다.Call Hooks from React function components전달되는 기능useEffect는 일반적인 Javascript 함수입니다.

다른 커스텀 훅 내부의 훅을 호출할 수 있습니다.

당신이 해야 할 일은 전화하는 것이다.useGetDocument컴포넌트 내부로 결과를 전달하고useEffect의존관계 배열

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

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

이렇게 하면docSnapshot변경, 사용자useEffect호출됩니다.

물론 다른 후크에도 후크를 호출할 수 있습니다.

일반 JavaScript 함수에서 Hooks를 호출하지 마십시오.대신 다음 작업을 수행할 수 있습니다.

✅ 리액트 기능 구성요소에서 후크를 호출합니다.

✅ Call Hooks from Custom Hooks(사용자 지정 후크) (다음 페이지에서 자세히 알아보겠습니다)

그렇지만.....

다른 후크 안에서 후크를 사용하지 않습니다.

useEffect에 전달한 것은 콜백이기 때문에 콜백 본문 내에서 커스텀 후크를 사용하고 있는 것이지 후크(useEffect)를 사용하고 있는 것은 아닙니다.

ESLint와 리액트 훅 플러그인을 사용하는 경우 다음과 같이 경고합니다.

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는 약속을 반환하지 않고 문서를 반환합니다.

후크를 호출할 때

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

처음에 정의되지 않은 상태로 반환되며, 그 후 @ApplePearPerson의 답변에 따라 후속 문서가 렌더링됩니다.

언급URL : https://stackoverflow.com/questions/59070930/is-it-possible-to-use-a-custom-hook-inside-useeffect-in-react

반응형