从外部使用 Apollo GraphQL refetch 方法

Using Apollo GraphQL refetch method from outside

我的渲染函数

translateFileAndRefetchQuery = (urn) => {
    translateFile(urn);
    // How do I refetch data from here?
  };

render() {
    const translateFormatter = (cell, row) => {
      return (
        <span>
          <Button
            onClick={() => translateFileAndRefetchQuery(row.urn)}
          >
            Translate
          </Button>
        </span>
      );
    };

    const columns = [
      {
        dataField: 'name',
        text: 'Name',
      },
      {
        dataField: 'lastUpdated',
        text: 'Last updated',
      },
      {
        dataField: 'lastTranslated',
        text: 'Translate',
        formatter: translateFormatter,
      },
    ];

    return (
      <>
        <h3>Models</h3>
        <h4>Root > Plans</h4>

        {this.state.plansFolderUrn != null &&
        <Query query={getProjects()}>
          {(data, refetch) => (
            <>
              <BootstrapTable
                keyField="name"
                data={data.projects}
                columns={columns}
              />
            </>
          )}
        </Query>
        }
      </>
    );
  }

我正在使用具有 refetch 方法的 apollo 数据获取器。我需要从 Query.

之外调用它

我该怎么做?

您可以在不同的回调中传递函数。我向 translateFormatter 添加了一个装饰器,以便不立即调用它:

translateFileAndRefetchQuery = (urn, refetch) => {
    translateFile(urn);
    refetch();
};

render() {
    const translateFormatter = refetch => (cell, row) => {
        return (
            <span>
                <Button
                    onClick={() => translateFileAndRefetchQuery(row.urn, refetch)}
                >
                    Translate
        </Button>
            </span>
        );
    };

    const getColumns = refetch => [
        {
            dataField: 'name',
            text: 'Name',
        },
        {
            dataField: 'lastUpdated',
            text: 'Last updated',
        },
        {
            dataField: 'lastTranslated',
            text: 'Translate',
            formatter: translateFormatter(refetch),
        },
    ];

    return (
        <>
            <h3>Models</h3>
            <h4>Root > Plans</h4>

            {this.state.plansFolderUrn != null &&
                <Query query={getProjects()}>
                    {(data, refetch) => (
                        <>
                            <BootstrapTable
                                keyField="name"
                                data={data.projects}
                                columns={getColumns(refetch)}
                            />
                        </>
                    )}
                </Query>
            }
        </>
    );
}