reactjs - 如何在组件外部调用 GraphQL

标签 reactjs graphql apollo

我已经制作了一堆使用 Query 组件调用 GraphQL 的 React 组件,一切正常。

在一个组件中,我需要从数据库获取一些初始数据,但没有任何视觉表示。

我尝试使用查询组件,但它似乎仅在渲染周期上触发。我尝试将其打包成一个函数,并在需要数据的组件中调用该函数。但代码/查询不会执行,因为没有可显示的组件。

如何在没有组件的情况下从数据库获取这些数据?

我找不到任何有关如何解决此问题的文档。但我不能 唯一一个这样做的人。

ApolloConsumer 或 ApolloProvider 是我问题的答案吗?

我正在处理 session 和 session 。 session 会持续几天,每天都有多个 session 。

我想要实现的是渲染一个页面,其中包含 X 个选项卡,每天一个。每个选项卡代表一天,并显示当天的 session 数。

我的 session 页面:

    import React from 'react';
import FullWidthTabs from '../components/Sessions';
import SessionTab from '../components/SessionTab';
import BwAppBar2 from '../components/BwAppBar2';
import ConferenceDays from '../components/ConferenceDays';


class SessionsPage extends React.Component {

    static async getInitialProps() {
        console.log("GetInitProps SessionsPage");
    }

    render() {
        let a = ConferenceDays();
        return (

                <div>
                    <BwAppBar2 />
                    {a}
                     <FullWidthTabs days={['2018-06-11', '2018-06-12', '2018-06-13']} day1={ < SessionTab conferenceId = "57" day = '2018-06-11' / > } 
                                   day2={ < SessionTab conferenceId = "57" day = '2018-06-12' / > } day3={ < SessionTab conferenceId = "57" day = '2018-06-13' / > }>
                    </FullWidthTabs>
                </div>
                );
        }
}
export default (SessionsPage);

此处的日期已硬编码在页面中,仅供测试。

但是为了知道 session 持续多少天,我必须找到 session 并决定开始和结束日期并生成其间的所有日期:

import React, { Component } from 'react'
import { graphql } from 'react-apollo'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'
import Link from '@material-ui/core/Link';
import { useQuery } from "react-apollo-hooks";

import conferencesQuery from '../queries/conferences'
import { Table, Head, Cell } from './Table'
import ConferenceCard from './ConferenceCard';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import moment from 'moment';


const CONFERENCE_QUERY = gql`
 query conference($conferenceId : ID!){
      conference(id: $conferenceId){
          title
          start_date
          end_date
     }    
}
`
let index = 0;
let loopDate = 0;
let dates = [];
let conferenceId = 57;

const ConferenceDays = () => (
<Query query={CONFERENCE_QUERY} variables={{conferenceId}}>
    {({ loading, error, data }) => {
                        if (loading)
                            return <div>Fetching</div>
                        if (error)
                            return <div>Error</div>
                        const startDate = moment(data.conference.start_date, 'x');
                        const endDate = moment(data.conference.end_date, 'x');

                        for (loopDate = parseInt(data.conference.start_date);
                                loopDate < parseInt(data.conference.end_date);
                                loopDate += 86400000) {

                            let aDate = moment(loopDate, 'x');
                            dates.push(aDate.format('YYYY-MM-DD').toString());
                        }
                        console.log(dates);
                        return(dates);
                    }}
</Query>);

export default ConferenceDays

但是这种做法不正确吗?

将 ConferenceDates 组件提升到层次结构中是否更正确?

最佳答案

您可以将 ApolloClient 的创建分离到一个单独的文件中,并使用 init 函数在 React 组件之外访问客户端。

import React from 'react';
import {
  ApolloClient,
  HttpLink,
  InMemoryCache,
} from "@apollo/client";

let apolloClient;

const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql",
  credentials: "same-origin",
});

function createApolloClient() {
  return new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache(),
  });
}

export function initializeApollo() {
  const _apolloClient = apolloClient ?? createApolloClient();
  if (!apolloClient) apolloClient = _apolloClient;

  return _apolloClient;
}

export function useApollo() {
  const store = useMemo(() => initializeApollo(initialState), [initialState]);
  return store;
}

然后你可以像这样使用这个外部组件:

const client = initializeApollo()
const res = await client.query({
  query: MY_QUERY,
  variables: {},
})

我自己没有尝试过这一点,但我认为这为您提供了如何进行此操作以及如何访问 ApolloClient 的想法。

关于reactjs - 如何在组件外部调用 GraphQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56340948/

相关文章:

javascript - 如何有条件地渲染react-bootstrap-table中的按钮? (每行的按钮)

vue.js - 为什么需要 graphql-tag 才能将 Apollo 与 Nuxt 结合使用?

graphql - 当所有请求都具有相同的 URL 时,如何在开发工具网络选项卡中区分 GraphQL 请求?

git - gh-pages d-构建 : failed at deploy script

javascript - 是的,多个复选框的验证

reactjs - 如何禁用阴影或更改 Material-UI 所需的组件

go - 使用 http 客户端通过 graphql 传递变量

javascript - GraphQL:从兄弟解析器访问另一个解析器/字段输出

graphql - 如何通过 GraphQL 从 json 文件中获取数据?

postgresql - 如何在 prisma 中将 createMany 与外键一起使用?