簡體   English   中英

Gatsby 中的 React 鈎子:無效的鈎子調用

[英]React hooks in Gatsby: Invalid hook call

嘗試從反應示例中實現自定義鈎子: https : //reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state ,但出現以下錯誤:

錯誤:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

在錯誤發生useEffect當我嘗試導入它作為一個自定義的鈎子usePrevious

我嘗試了以下操作:驗證 react-dom 和 react 在同一版本上react-dom@16.8.5 react@16.8.5

確認我只有一個版本的 React

我也相信代碼沒有違反任何鈎子規則。

還嘗試在 stackoverflow 上查看相關問題。

代碼:

// file: use-previous.js

import { useRef, useEffect} from "React"

export const usePrevious = (value) =>  {

    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });




    return ref.current;
}
// file: layout.js

import React, { useState, useEffect } from "react"

import Header from "./header/header"

import { useFacetsData } from "../hooks/use-facets-data"
import { usePrevious } from "../hooks/use-previous"


export default ({ children, ...props }) => {

    const [ searchValue, setSearchValue ] = useState("")

    const [ facetsSelected, setFacetsSelected ] = useState([])

    const facets = useFacetsData()


    const oldSearchValue = usePrevious(searchValue)
    // const oldFacetsSelected = usePrevious(facetsSelected)

    useEffect(() => {
        // if new searchvalue or new facetvalue

        // if (searchValue !== oldSearchValue || facetsSelected !== oldFacetsSelected) makeSearch()
    }) 

    function makeSearch() {
        console.log('make search')

        // move to searchpage 
    }

    function handleSearchChange(search) {
        setSearchValue(search)
    }

    function handleFacetChange(facets) {
        setFacetsSelected(facets)
    }   

    return   (
        <div>
            {/* Main sticky header */}
            <Header 
                facets={ facets } 
                onSearchChange={ handleSearchChange } 
                onFacetChange={ handleFacetChange } >
            </Header>

            {/* route content */}
           {React.cloneElement(children, { facets })}
        </div>
    )
}

您在usePrevious hooks 文件中的導入不正確。 useRefuseEffect應該從'react'而不是React導入;

import { useRef, useEffect} from "react"

我遇到了同樣的問題,請按照此步驟解決問題

https://reactjs.org/warnings/invalid-hook-call-warning.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM