如何在 useLazyLoadQuery 中跳过请求

how to skip request in `useLazyLoadQuery`

如何在 useLazyLoadQuery 中跳过 request/query。

import { useLazyLoadQuery } from 'react-relay/hooks';

const id = props.selectedId // id can be a number or null
const user = useLazyLoadQuery(query, {id}) // skip query/request network if id is null

您可以使用@skip or @include directive。如果在指令条件下查询最终为空,则不会发出网络请求。考虑这个例子:

import { useLazyLoadQuery } from 'react-relay/hooks';

function MaybeUser(props) {
  const { userId } = props;
  //         is optional/nullable

  useLazyLoadQuery(
    graphql`
      query MaybeUserQuery($userId: ID!, $skip: Boolean!) {
        user(id: $userId) @skip(if: $skip) {
          fullName
        }
      }
    `,
    {
      userId: userId || '', // we need to pass something because of the query $userId type decleration
      skip: !userId,        // skip when there is no user ID
    },
  );

  return <magic />;
}

userId 生成空 MaybeUserQuery 导致 无网络请求