0

我正在尝试手动执行查询,因此遵循官方 Apollo 文档。我看不出文档和我的代码之间有任何区别,但是,我总是收到错误“重新渲染太多”。

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;
4

2 回答 2

0

Bad Apollo example!

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);
}

Using state is unnecessary (even with condition forces additional rerendering) - you can read data directly from data (it's just a private variable):

return (
  <div>
    {data && <div>{data.contactInformation}</div>}
于 2020-03-01T11:19:50.600 回答
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;

于 2020-08-05T19:12:08.427 回答