我正在尝试Execute queries manually,因此也遵循了阿波罗官方文档。我看不到文档和代码之间的任何区别,但是,我总是收到错误“重新渲染太多”。
const FEED_QUERY = gql`
query contactAccessKey($accessKey: String!) {
contactAccessKey(accessKey: $accessKey) {
id
contactInformation
belongsTo {
id
username
email
}
}
}
`;
function AccessKeySeeEmergencyContact() {
const [contact, setContact] = useState("");
const [getContactInformation, { loading, data }] = useLazyQuery(FEED_QUERY);
if (loading) return <p>Loading ...</p>;
if (data && data.contactAccessKey) {
setContact(data.contactAccessKey);
}
const accessKeyCode = "34a60667-80e3-4c97-9ded-15875d6507b1";
return (
<div>
{contact && <div>{contact.contactInformation}</div>}
<button
onClick={() =>
getContactInformation({ variables: { accessKey: accessKeyCode } })
}
>
Click me!
</button>
</div>
);
}
export default AccessKeySeeEmergencyContact;
答案 0 :(得分:0)
const [contact, setContact] = useState("");
const [getContactInformation, { loading, data }] = useLazyQuery(FEED_QUERY);
if (loading) return <p>Loading ...</p>;
// additional condition to avoid endless rerendering
if (!contact && data && data.contactAccessKey) {
setContact(data.contactAccessKey);
}
不需要使用状态(即使有条件的情况下也需要重新渲染)-您可以直接从data
(只是一个私有变量)读取数据:
return (
<div>
{data && <div>{data.contactInformation}</div>}
答案 1 :(得分:0)
useApolloClient 具有返回Promise的函数,我已经使用此函数解决了类似的问题。 请注意,我刚刚复制并编辑了您的代码,可能会出现一些语法错误。一切顺利。
import { useApolloClient } from '@apollo/client';
function AccessKeySeeEmergencyContact() {
const [contact, setContact] = useState('');
const client = useApolloClient(); // this gives an ApolloClient
const accessKeyCode = '34a60667-80e3-4c97-9ded-15875d6507b1';
return (
<div>
{contact && <div>{contact.contactInformation}</div>}
<button
onClick={async () => {
const { data } = await client.query({
query: FEED_QUERY,
variables: { accessKey: accessKeyCode },
});
console.log(data);
}}>
Click me!
</button>
</div>
);
}
export default AccessKeySeeEmergencyContact;