RefetchContainer

RefetchContainer 的第一次渲染就像 FragmentContainer一样, 但可以选择使用不同的变量执行新查询,并在请求返回时渲染该查询的响应。

this.props.relay 导出以下API以执行refetch查询:

type Variables = {[name: string]: any};
type RefetchOptions = {
  force?: boolean, // Refetch even if already fetched this query and variables.
};
type Disposable = {
  dispose(): void,
};

/**
 * Execute the refetch query
 */
refetch: (
  refetchVariables: Variables | (fragmentVariables: Variables) => Variables,
  renderVariables: ?Variables,
  callback: ?(error: ?Error) => void,
  options?: RefetchOptions,
) => Disposable,
  • refetchVariables 是一包变量或一个函数,它接收以前的片段变量并返回新的变量。
  • renderVariables 是一个可选的参数,它告诉Relay在获取组件后重新渲染时要使用哪些变量。没有这个参数, refetchVariables 将会被使用。您可以使用它来进行更高级的使用,例如,实现分页,您可以在其中获取带有变量的附加页面 {first: 5, after: '...'}, 但您可以使用它来呈现完整的集合 {first: 10}.
  • 当您呼叫 dispose() 取消 重新获取的时候,它返回一个 Disposable

Example #

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

class FeedStories extends React.Component {
  render() {
    return (
      <div>
        {this.props.feed.stories.edges.map(
          edge => <Story story={edge.node} key={edge.node.id} />
        )}
        <button
          onPress={this._loadMore}
          title="Load More"
        />
      </div>
    );
  }

  _loadMore() {
    // Increments the number of stories being rendered by 10.
    const refetchVariables = fragmentVariables => ({
      count: fragmentVariables.count + 10,
    });
    this.props.relay.refetch(refetchVariables, null);
  }
}

module.exports = createRefetchContainer(
  FeedStories,
  {
    feed: graphql`
      fragment FeedStories_feed on Feed
      @argumentDefinitions(
        count: {type: "Int", defaultValue: 10}
      ) {
        stories(first: $count) {
          edges {
            node {
              id
              ...Story_story
            }
          }
        }
      }
    `
  },
  graphql`
    query FeedStoriesRefetchQuery($count: Int) {
      feed {
        ...FeedStories_feed @arguments(count: $count)
      }
    }
  `,
);