【问题标题】:How to render a long list in react-relay?如何在反应中继中呈现长列表?
【发布时间】:2016-05-02 15:38:30
【问题描述】:

一个用于 react-web 的惰性滚动列表组件 通过分页获取支持中继连接, 同时提供良好的性能和内存特性。

两件事要管理

  • 通过提供分页参数进行查询、操作中继存储来获取数据
  • 组件渲染、虚拟 DOM 操作

是否有一些特殊的列表组件可以很好地处理这个问题? 是否有实施这种通用机制的既定模式?

【问题讨论】:

    标签: reactjs relayjs graphql


    【解决方案1】:

    这种模式几乎是连接的代表性场景。这是一个假设的<PostsIndex> 组件,它显示带有“加载更多”按钮的帖子列表。如果您不想在 isLoading 状态下显式更改 UI,您可以删除构造函数和 setVariables 回调。添加基于视口的无限滚动也不难;您只需要将滚动监听器连接到您的 setVariables 呼叫。

    class PostsIndex extends React.Component {
      constructor(props) {
        super(props);
        this.state = {isLoading: false};
      }
    
      _handleLoadMore = () => {
        this.props.relay.setVariables({
          count: this.props.relay.variables.count + 10,
        }, ({ready, done, error, aborted}) => {
          this.setState({isLoading: !ready && !(done || error || aborted)});
        });
      }
    
      render() {
        return (
          <div>
            {
              this.props.viewer.posts.edges.map(({node}) => (
                <Post key={node.id} post={node} />
              ))
            }
            {
              this.props.viewer.posts.pageInfo.hasNextPage ?
                <LoadMoreButton
                  isLoading={this.state.isLoading}
                  onLoadMore={this._handleLoadMore}
                /> :
                null
            }
          </div>
        );
      }
    }
    
    export default Relay.createContainer(PostsIndex, {
      initialVariables: {
        count: 10,
      },
      fragments: {
        viewer: () => Relay.QL`
          fragment on User {
            posts(first: $count) {
              edges {
                node {
                  id
                  ${Post.getFragment('post')}
                }
              }
              pageInfo {
                hasNextPage
              }
            }
          }
        `,
      },
    });
    

    【讨论】:

    • isLoading 设置为true 时,LoadMoreButton 是否不会调用this._handleLoadMore
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 2021-06-03
    • 1970-01-01
    • 2019-05-13
    • 2022-11-10
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多