2022年6月8日 React使用umi.js报错Invalid hook call
报错详情
在写React项目的Demo的时候,使用umi中useHistory,调用运行时,报了以下错误
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
翻译如下:
无效的挂钩调用。 钩子只能在函数组件的主体内部调用。 这可能由于以下原因之一而发生:
1. React 和渲染器的版本可能不匹配(例如 React DOM)
2. 你可能违反了 Hooks 规则
3. 你可能在同一个应用程序中拥有多个 React 副本
代码
import { doLogin } from '@/api/user/user';
import { Button, Form, Input, message } from 'antd';
import { useHistory } from 'umi';
const history = useHistory();
const login = (user: API.IUser) => {
doLogin(user).then(res => {
console.log(res);
if (res.code === 200) {
message.success({
content: "用户" + user.username + "登录成功",
onClose: () => {
history.push("/")
}
});
} else {
message.error("登录失败");
}
})
}
function Index() {
return (
<>
<Form
onFinish={login}
labelCol={{ span: 6 }}
wrapperCol={{ span: 12 }}
>
<Form.Item
label={'用户名'} name={'username'}
rules={[
{
required: true,
type: 'string',
message: '用户名不允许为空'
}
]}
>
<Input />
</Form.Item>
<Form.Item
label={'密码'} name={'password'}
rules={[
{
required: true,
type: 'string',
message: '密码不允许为空'
},
{
max: 20,
min: 10,
message: '密码长度在10~20之间'
},
{
}
]}
>
<Input.Password />
</Form.Item>
<Form.Item wrapperCol={{ offset: 6, span: 12 }}>
<Button type="primary" htmlType="submit">
登录
</Button>
<Button type="default" style={{ marginLeft: 10 }} htmlType="reset">
重置
</Button>
</Form.Item>
</Form>
</>
);
}
export default Index;
解决
排查后发现,原来是
const history = useHistory();
这句初始化代码写在了组件外面,导致异常。
截图来自链接:react-hooks原理
将代码移入组件内部,错误解决了,代码如下
import { doLogin } from '@/api/user/user';
import { Button, Form, Input, message } from 'antd';
import { useHistory } from 'umi';
function Index() {
const history = useHistory();
const login = (user: API.IUser) => {
doLogin(user).then(res => {
console.log(res);
if (res.code === 200) {
message.success({
content: "用户" + user.username + "登录成功",
onClose: () => {
history.push("/")
}
});
} else {
message.error("登录失败");
}
})
}
...
}
export default Index;