RelayJS 无限滚动

RelayJS infinite scroll

我试图在我的 React-Relay 前端中进行无限滚动分页,但没有成功。

此刻,我有这个 React 组件...

class List extends Component {
  state = { loading: false };

  componentDidMount() {
    window.onscroll = () => {
      if (!this.state.loading
              && (window.innerHeight + window.scrollY)
              >= document.body.offsetHeight) {

        this.setState({loading: true}, () => {
          this.props.relay.setVariables({
            count: this.props.relay.variables.count + 5
          }, (readyState) => {
            if (readyState.done) {
              this.setState({ loading: false });
            }
          });
        });
      }
    }
  }

  render() {
    return (
      <div>
        {this.props.viewer.products.edges.map(function(product, i) {
          return (<Item key={i} product={product.node} />);
        })}
      </div>
    );
  }
};

...包裹在中继容器中

export default Relay.createContainer(List, {
  initialVariables: {
    count: 5
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        products(first: $count) {
          total
          edges {
            node {
              ${Item.getFragment('product')}
            }
          }
        }
      }
    `,
  }
});

这背后的逻辑似乎很简单。如果您到达某个 scrollY 位置,请为 count 变量设置一个新的增量值,这会扩展您的边列表。

但是这个概念会导致一种情况,一开始我查询数据库的前 5 条记录,但最近当我不断滚动时,将查询 N+5 条记录。最后我会查询整个数据库table(几千条记录)!这是相当不可接受的table.

所以我正在尝试实现 cursors,但我不知道如何从连接中获取数据并扩展结果。这种方法 returns 我一个 "paginated" 列表。


此外,当我向下滚动时,上面的代码给了我这个错误

resolveImmediate.js?39d8:27 Uncaught Invariant Violation: performUpdateIfNecessary: Unexpected batch number (current 19, pending 18)

我将非常感谢任何帮助或示例!

问题已解决!

关于我每次滚动一遍又一遍地获取N+5条记录的问题,似乎Relay很聪明,因为它通过查询自动“分页”我的连接cursor 并在我的连接中管理 after arg。

在我后端 graphql-sequelize 的帮助下,它简单地变成了这个查询

SELECT ... FROM product ORDER BY product.id ASC LIMIT 5 OFFSET 10

这实际上解决了我关于性能的第一个问题。 :)

所以我的 Relay.QL 查询已经隐藏在 运行 中

query ListPage_ViewerRelayQL($id_0:ID!) {
  node(id:$id_0) {
    ...F1
  }
}
fragment F0 on Product {
  id,
  title,
  price
}
fragment F1 on Viewer {
  _products4tSFq4:products(after:"YXJyYXljb25uZWN0aW9uJDUkNA==",first:5) {
    edges {
      cursor,
      node {
        id,
        ...F0
      }
    },
    pageInfo {
      hasNextPage,
      hasPreviousPage
    }
  },
  id
}

当我 运行 在我的 GraphQL 后端执行此查询时,它返回了空结果

{
  "data": {
    "node": null
  }
}

然后我立刻意识到问题出在哪里以及为什么我的中继崩溃了。

问题在于重新获取查看器。我没有正确实施 nodeDefinitions,当查看器 ID 命中 idFetchertypeResolver 时,它失败并返回 null。在那之后,在客户端,Relay 无法完成我的连接的重新获取并崩溃了!

经过小规模修复和 后端修复,我的无限滚动效果非常好! :)