Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
·
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
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
报错原因
具体报错如上,错误原因是,没有把 hook 当做一个 Function Component ,而是当做了 Function 进行调用。下面是调用过程:
import React, { Component, Fragment } from 'react';
import { Example } from './Example.js'; //引入 hook 组件
class App extends Component {
render() {
return (
<Fragment>
<div>some thing...</div>
{
Example() //执行
}
</Fragment>
);
}
}
export default App;
hook 组件部分如下:
import React, { useState } from 'react';
export function Example() {
const [num, updateNum] = useState(0)
return <p onClick={() =>updateNum(num => num + 1)}>{num}</p>
}
解决方法
正确的调用方式应该是组件式的调用:
import React, { Component, Fragment } from 'react';
import { Example } from './Example.js';
class App extends Component {
render() {
return (
<Fragment>
<div>some thing...</div>
<Example />//写成一个组件,而不是执行函数
</Fragment>
);
}
}
export default App;
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐

所有评论(0)