![](/img/trans.png)
[英]React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component
[英]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.