React函数组件调用报错:Invalid hook call问题排查求助
问题描述
我在外部组件中通过const current = Question();的方式调用自定义Question函数组件,组件代码如下:
export const Question = () => { const [text, setText] = useState("None"); return ( <> <div className="row"> <div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"> <span>{text}</span> </div> </div> </> ) }
执行后触发错误:
Uncaught Error: 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
我并未在普通JS函数中调用Hook,请问问题出在哪里?
问题原因与解决方法
问题出在组件调用方式上:const current = Question(); 是直接执行函数,而非让React处理组件渲染逻辑。
React函数组件必须通过JSX语法(<Question />)或React.createElement(Question)调用,这样React才能识别这是组件,进而正确处理内部的Hooks(比如useState)。直接执行函数时,useState等同于在普通函数中被调用,违反了Hook的使用规则,因此触发报错。
解决方法:将调用方式改为JSX语法:
const current = <Question />;
或者在需要渲染的位置直接使用<Question />即可。
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

