问题描述
两种情况:
- 在项目中正常的函数组件可正常使用
hooks
例如简单的计时器:
// 正常工作:
...
<Count />
...
const Count = () => {
const [num, increaceNum] = useState(0);
return (
<>
<Button onClick={() => increaceNum(num + 1)}>数字增加:</Button>{num}
</>
);
};
- 在项目中使用UI库的API渲染组件的函数组件不可正常使用
hooks
指的是:
- antd里的
confirm
api: https://ant.design/components... - zent里的
openDialog
api: https://youzan.github.io/zent...
...
<Count />
...
const Count = () => {
const [num, increaceNum] = useState(0);
openDialog({
dialogId: 1,
title: '使用 openDialog 直接打开对话框',
children: <><div onClick={() => increaceNum(num + 1)}>增加</div>{num}</>,
footer: <Button onClick={() => closeDialog(1)}>关闭</Button>,
});
}
报错信息
图片
文本
react-dom.development.js:35 Uncaught Invariant Violation: 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
希望解决
- 在API渲染的函数组件里可正常使用hooks,否则只能用回
class
了
这个只是个函数,不是组件。
函数组件和函数还是有所区别的。前者会被React编译,最终执行的实质上是React编译后的函数;而后者在未执行时,React可能都不知道它是什么东西。
至于解决方案,可以把函数改写成函数组件,或者采用单例模式来管理其状态。