React Relay Fragment 中的<fragment_name >$key 和<fragment_name >$data 有什么区别?

问题描述 投票:0回答:1

我正在学习react relay库,在阅读文档Relay - A Guided Tour - Fragments时,我对这部分感到困惑:

Relay will automatically generate Flow types for any declared 
fragments when the compiler is run, so you can use these types to 
declare the type for your Component's props.

The generated Flow types include a type for the fragment reference, 
which is the type with the $key suffix: <fragment_name>$key, and a 
type for the shape of the data, which is the type with the $data 
suffix: <fragment_name>$data; these types are available to import 
from files that are generated with the following name: 
<fragment_name>.graphql.js.
  1. fragment reference
    是什么意思?是指这个片段的生成流类型吗(
    UserComponent_user
    )?或者查询生成的流类型包含/使用片段(
    User
    )?
  2. 带$key后缀的
    type
    是什么?片段还是查询?
  3. 带$data后缀的
    type
    是什么?片段还是查询?
javascript reactjs graphql relayjs
1个回答
0
投票

考虑这个例子

import type {UserComponent_user$key} from 'UserComponent_user.graphql';

const React = require('React');

const {graphql, useFragment} = require('react-relay');

type Props = {
  user: UserComponent_user$key,
};

const userFragment = graphql`
  fragment UserFragment_user on User {
    name
    age
    profile_picture(scale: 2) {
      uri
    }
  }
`;

function UserComponent(props: Props) {
  const data = useFragment(
    userFragment, props.user
  );

  return (
    <>
      <h1>{data.name}</h1>
      <div>
        <img src={data.profile_picture?.uri} />
      </div>
    </>
  );
}

module.exports = UserComponent;

请记住,片段是 GraphQL 中的可重用单元,它们不能自行获取。所以我们需要将它包含在一个查询中。注意单个片段仍然可以被多个查询包含。

/**
 * App.react.js
 *
 * Query Component
 */

import type {AppQuery} from 'AppQuery.graphql';
import type {PreloadedQuery} from 'react-relay';

const React = require('React');
const {graphql, usePreloadedQuery} = require('react-relay');

const UserComponent = require('./UserComponent.react');

type Props = {
  appQueryRef: PreloadedQuery<AppQuery>,
}

function App({appQueryRef}) {
  const data = usePreloadedQuery<AppQuery>(
    graphql`
      query AppQuery($id: ID!) {
        user(id: $id) {
          name

          # Include child fragment:
          ...UserComponent_user
        }
      }
    `,
    appQueryRef,
  );

  return (
    <>
      <h1>{data.user?.name}</h1>
      {/* Render child component, passing the fragment reference: */}
      <UserComponent user={data.user} />
    </>
  );
}

您可以看到 AppQuery 正在获取

user
字段下包含的片段的数据。现在,为了获取该数据,我们需要一个指向它的指针。片段引用什么也不是,就是那个指针。 我们将
data.user
(这指的是主查询中的片段传播,它充当具有 $key 流类型的片段引用)到 UserComponent 中,UserComponent 将片段定义应用于该键并获取数据。

带 $key 前缀的类型不过是流类型,是片段引用的类型。

带有 $data 前缀的类型不过是流类型,它是片段定义中数据的类型。

© www.soinside.com 2019 - 2024. All rights reserved.