React钩子:使用useQuery时钩子调用无效



我有一个带有提交按钮的表单,当我提交表单时,我正在调用lookup函数。当代码符合graphQl时,它返回Invalidhooks错误。

版本

"react": "^17.0.2",
"react-dom": "^17.0.2",

代码:

import React, { useEffect, useState, useCallback } from "react";
import ReactDOM from "react-dom";
import { Button, Form, Input, Row, Card, Col } from "antd";
import { SearchOutlined, LoginOutlined } from "@ant-design/icons";
import { useQuery, useMutation, gql } from "@apollo/client";
const IDP_LOOKUP = gql`
query getBusiness($name: String!) {
business(name: $name) {
id
name
domain {
DomainType
... on Domains {
DomainName
}
}
}
}
`;
const lookup = (values) => {
let DomainName = "https://" + values.Orgname + ".com";
const { data, loading, error } = useQuery(IDP_LOOKUP, {
variables: {
name: DomainName
}
});
};
const Login = () => {
return (
<div>
<Card size="small" title="Okta Login">
<Row type="flex">
<Col lg={24}>
<Form name="lookup_login" className="login-form" onFinish={lookup}>
<Row gutter={16} align="center" justify="center" type="flex">
<Col lg={18}>
<Form.Item
label="Org Name"
name="Orgname"
rules={[
{
required: true,
message: "Please enter org name!"
}
]}
>
<Input addonBefore="https://" addonAfter=".com" />
</Form.Item>
</Col>
<Col lg={6}>
<Form.Item>
<Button
type="primary"
htmlType="submit"
className="login-form-button"
>
<SearchOutlined /> Lookup
</Button>
</Form.Item>
</Col>
</Row>
</Form>
</Col>
</Row>
</Card>
</div>
);
};

错误:

错误:钩子调用无效。钩子只能称为身体内部功能组件。以下情况之一可能会发生这种情况原因:

  1. React和渲染器的版本可能不匹配(例如React DOM(
  2. 你可能违反了胡克规则
  3. 您可能在同一应用程序中有多个React副本请参阅https://reactjs.org/link/invalid-hook-call有关如何调试的提示并解决此问题
Apollo有一个useLazyQuery钩子,您可以在组件渲染后调用它。这返回一个元组,其中第一项是一个函数,然后您可以从处理程序中调用该函数来实际执行查询。

我认为应该这样做:

const Login = () => {    
const [lookupIdp, { called, loading, data }] = useLazyQuery(IDP_LOOKUP);
const lookup = (values) => {
let DomainName = "https://" + values.Orgname + ".com";
lookupIdp({
variables: {
name: DomainName
}
})
};
return (
<div>

您应该在Login组件内部调用hook/lookup函数,您可以在函数外部声明常量变量,但不能声明hook。

const Login = () => {
const lookup = (values) => {
let DomainName = "https://" + values.Orgname + ".com";
const { data, loading, error } = useQuery(IDP_LOOKUP, {
variables: {
name: DomainName
}
});
return <></>
};

你明白了吗?虽然你的代码不完整,但为了更好的解释,因为我看不到你的变更处理程序

最新更新