簡體   English   中英

為什么我在以下代碼中收到此錯誤“反應無效的掛鈎調用。只能在 function 組件的主體內部調用掛鈎”?

[英]Why am i getting this error "react Invalid hook call. Hooks can only be called inside of the body of a function component" in the following code?

import React,{ useEffect, useState} from 'react';
import { useLocation } from 'react-router-dom';
import ReactPlayer from 'react-player';

import { useResultContext } from '../contexts/ResultContextProvider';

export const Results = () => {
  const {getResults, results, isLoading, searchTerm} = useResultContext();
  const location = useLocation();
  const [num, setNum] = useState(10);

  const changeNum=()=>{
    setNum(num+10);
    console.log(num)
    Results();
}

  useEffect(()=>{
    if(searchTerm){
    if (location.pathname ==='/videos') {
      getResults(`/search/q=${searchTerm} videos&num=${num}`)
    }else{
      getResults(`${location.pathname}/q=${searchTerm}&num=${num}`)
    }
  }
  },[location.pathname, searchTerm, num, getResults]);


  switch (location.pathname) {
    case '/search':
      return (<><div className='flex flex-wrap justify-between space-y-6 sm:px-56 overflow-hidden pb-4 '>
        {
          results?.results?.map(({link, title, description}, index)=>(
            <div key={index} className='md:w-3/5 w-full'>
              <a href={link} target="_blank" rel="noreferrer">
                <p className='text-sm text-green-700'>
                  {link.length>50? link.substring(0,50): link}
                </p>
                <p className='text-lg hover:underline dark:text-blue-300 text-blue-700'>
                  {title}
                </p>
              </a>
              {description.length>15?
                <p>
                  {description}
                </p>:''}
            </div>
          ))
        }
      </div>
      <div onClick={changeNum} className='absolute bg-gray-200 border border-gray-400 py-3 px-10 rounded-full -mt-5 left-96 cursor-pointer active:bg-gray-300 dark:bg-gray-700 '>
        More Results
      </div>
      </>);
    default: return 'ERROR';
  }
  
};

我已經開始學習反應,已經兩天了,我一直無法解決這個問題。

我正在嘗試克隆谷歌搜索引擎,在這個項目中,我使用谷歌搜索 api 獲得結果,一開始顯示 10 個結果,然后每次單擊調用“更多結果”按鈕時都希望增加 10 個changeNum' function 每次通過單擊按鈕調用 function 時,它使用 'setNum' 將 10 值添加到 'num'。

編輯:我通過刪除一些案例來縮短代碼

const changeNum=()=>{
setNum(num+10);
console.log(num)
Results();   <--------
}

像這樣調用您的功能組件是導致錯誤的原因。 不需要此行,因為您的組件將在您更新 state 時更新。

暫無
暫無

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

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