【问题标题】:State Change causing GraphQL runs again in react导致 GraphQL 的状态更改在反应中再次运行
【发布时间】:2020-01-19 08:20:17
【问题描述】:

我在使用 graphQL 时看到了一种反应场景。在下面的代码中,每当代码到达 onPaginationChange 方法时,它也会到达 getVariables 方法并最终调用 GraphQL 来获取数据。它是怎么发生的?

onPaginationChange 方法中的状态变化是否会导致所有依赖状态的地方刷新?是反应的东西吗?或者一些graphQL的东西?在下面的代码中,我提供了我认为有用的主要内容。我已经删除了 Table 的确切实现,因为我认为这个问题不需要回答。

import React, { Component } from "react";
import gql from "graphql-tag";
import { Query } from "react-apollo";

export const LIST_ITEMS = gql`
  query list(
    $pageIndex: Int
    $limit: Int
  ) {
    listItems(
      limit: $limit
      pageIndex: $pageIndex
    ) {
      items {
        name
        description
      }
      totalCount
    }
  }
`;

export class ManageItems extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPageIndex: 1,
      pagesCount: 1,
      pageSize: 30
    };
  }

  getVariables() {
    // It comes here whenever there onPaginationChange function is called. HOW?
    return {
      pageIndex: this.state.currentPageIndex - 1,
      limit: this.state.pageSize
    };
  }

  onPaginationChange({ detail }) {
    this.setState({
      currentPageIndex: detail.currentPageIndex,
      pageSize: detail.pageSize
    });
  }

  render() {
    const { t } = this.props;

    return (
      <Query
        query={LIST_ITEMS}
        variables={this.getVariables()}}
      >
        {({ loading, error, data }) => {
          if (error)
            return ("error");

          return (
            <Table onPaginationChange={this.onPaginationChange.bind(this)}>
            </Table>
          );
        }}
      </Query>
    );
  }
}

export ManageItems;

【问题讨论】:

  • 有什么好的文档或视频可以推荐阅读或观看吗?我在网上读了一些东西。很难理解/记住所有这些概念。有时,它们也没有被覆盖。

标签: reactjs graphql


【解决方案1】:

当您在 React 中更新状态时(使用 this.setState()),组件会重新渲染。这就是this.getVariables() 将被执行的原因。如果变量与您之前输入查询的变量不同,apollo 将获取您的后端。

我建议你从react-apollo 中查看fetchMore,或者将你的 GraphQL 查询放在一个只处理一个页面的组件中。

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 2014-05-24
    • 2023-01-26
    • 2020-07-28
    • 2020-04-23
    相关资源
    最近更新 更多