【问题标题】:How to navigate without cursors in a connection如何在连接中不使用光标进行导航
【发布时间】:2016-03-15 12:56:42
【问题描述】:

我有一个数组/表,可以说 10000 个项目。

现在我尝试在我的反应中继客户端中显示从索引 4000 到 4010 的项目。

但目前connectionArgs 只允许使用cursors 导航,但我不想在到达项目 4000 之前分页。

如何使用 GraphQL 查询导航到给定的偏移量?

谢谢

【问题讨论】:

    标签: reactjs relayjs graphql-js


    【解决方案1】:

    您可以通过在 Relay.Container 片段和服务器 GraphQL 架构中声明变量来使用 this.props.relay.setVariable 将变量值传递给服务器端。

    示例代码如下。特别注意标有注意:

    的部分

    在您的客户端:

    // Your React component 
    class ItemList extends React.Component {
      constructor(props) {
        super(props);
        this.state = { startItemIndex: 0 };
      }
    
      nextPage() {
        const _nextPageItemIndex = this.state.startItemIndex + itemCountOnPage;
        // NOTE: Call this.props.relay.setVariables to force re-fetch 
        this.props.relay.setVariables({ startItemIndex: _nextPageItemIndex });
        this.setState({ startItemIndex: _nextPageItemIndex });
      }
      ...
    }
    
    // Your Relay data declaration
    Relay.createContainer(ItemList, {
      initialVariables: {
        itemStartIndex:  0,
      },
      fragments: {
        itemList: () => Relay.QL`
          // NOTE: Declare your variable in the GraphQL fragment
          fragment on ItemList(itemStartIndex: $itemStartIndex) {
            id,
            listName,
            items,
            ...
          }
        `
      }
    }
    

    在您的服务器端,在您的 GraphQL 架构中:

    var ItemListType = new GraphQLObjectType({
      name: 'ItemList',
      fields: () => ({
        listName: {type: GraphQLString},
        items: ...
      }),
    });
    
    // App is what your Route will query, and it holds your itemList
    // Relay.QL`
    //   query GameQuery {
    //     itemList
    //   }
    // `
    var AppType = new GraphQLObjectType({
      name: 'App',
      fields: () => ({
        itemList: {
          // NOTE: This is where your variables will appear
          args: {
            itemStartIndex: {type: GraphQLInt},
          },
          type: new GraphQLList(ItemListType),
          ...
          resolve: (appObj, args) => {
            // NOTE: Use args.itemStartIndex to pull out your list
          }
        },
      }),
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多