reactjs - 在 Next.js 应用程序中使用 GraphQL 的推荐方法

标签 reactjs graphql next.js react-apollo strapi

在我的应用中,我使用以下 NPM 模块来玩 Strapi , GraphQLNext.js :

下一步,我将创建 Apollo 配置文件,示例如下:

import { HttpLink } from "apollo-link-http";
import { withData } from "next-apollo";

const config = {
  link: new HttpLink({
    uri: "http://localhost:1337/graphql",
  })
};
export default withData(config);

然后在类组件内,我使用静态方法 getInitialProps() 通过 GraphQL 查询从 Strapi 获取数据。

一切都很好,但也许还有另一种更好的方法,通过 React hooks 或任何其他方法?

最佳答案

我为 Next.js 和 GraphQL 找到了一个更好的钩子(Hook)解决方案。

我想和你分享。让我们开始吧。

注意:我假设您已经安装了 Next.js 应用程序。如果没有请按照此guide .

要构建此解决方案,我们需要:

1.运行npm命令:

npm install --save @apollo/react-hooks apollo-cache-inmemory apollo-client apollo-link-http graphql graphql-tag isomorphic-unfetch next-with-apollo

2.创建Appolo配置文件,例如。在文件夹 ./config 中并将其命名为 appollo.js。文件代码如下:

import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import withApollo from "next-with-apollo";
import { createHttpLink } from "apollo-link-http";
import fetch from "isomorphic-unfetch";

const GRAPHQL_URL = process.env.BACKEND_URL || "https://api.graphql.url";

const link = createHttpLink({
  fetch,
  uri: GRAPHQL_URL
});

export default withApollo(
  ({ initialState }) =>
    new ApolloClient({
      link: link,
      cache: new InMemoryCache()
        .restore(initialState || {})
    })
);

3../pages文件夹中使用以下代码创建_app.js文件(一种包装器):

import React from "react";
import Head from "next/head";
import { ApolloProvider } from "@apollo/react-hooks";
import withData from "../config/apollo";

const App = ({ Component, pageProps, apollo }) => {
  return (
    <ApolloProvider client={apollo}>
      <Head>
        <title>App Title</title>
      </Head>
      <Component {...pageProps} />
    </ApolloProvider>
  )
};

export default withData(App);

4.创建可重用的查询组件,例如。 ./components/query.js

import React from "react";  
import { useQuery } from "@apollo/react-hooks";

const Query = ({ children, query, id }) => {  
  const { data, loading, error } = useQuery(query, {
    variables: { id: id }
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {JSON.stringify(error)}</p>;
  return children({ data });
};

export default Query;

5.为通过 GraphQL 获取的数据创建一个组件

import React from "react";
import Query from "../components/query";
import GRAPHQL_TEST_QUERY from "../queries/test-query";

const Example = () => {  
  return (
    <div>
      <Query query={GRAPHQL_TEST_QUERY} id={null}>
        {({ data: { graphqlData } }) => {
          return (
            <div>
              {graphqlData.map((fetchedItem, i) => {
                return (
                  <div key={fetchedItem.id}>
                    {fetchedItem.name}
                  </div>
                );
              })}
            </div>
          );
        }}
      </Query>
    </div>
  );
};

export default Example;

6../queries/test-query 中创建 GraphQL 查询。 注意:我假设我们可以通过 GraphQL 访问示例数据和属性 idname

import gql from "graphql-tag";

const GRAPHQL_TEST_QUERY = gql`
  query graphQLData {
    exampleTypeOfData {
      id
      name
    }
  }
`;

export default GRAPHQL_TEST_QUERY;

7. 要显示我们的结果,请在 ./pages 文件夹中创建 index.js 文件(主页),代码如下:

import Example from './components/example';

const Index = () => <div><Example /></div>

export default Index;

仅此而已..根据需要享受并扩展此解决方案..

关于reactjs - 在 Next.js 应用程序中使用 GraphQL 的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60852061/

相关文章:

javascript - 根据状态更改按钮的类名无法正常工作

reactjs - 如何提取 "=>"到函数模型

javascript - 异步/等待不适用于 react js( Hook )

neo4j - GraphQL是否否定了对图数据库的需求

reactjs - Nextjs 和 Context API

javascript - gitlab 上的 CI/CD 无法使用 babel-loader 进行编译

java - android:如何增加购物车中商品的数量

python - 如何在 Graphene Python 突变中设置 cookie?

Next.js 忽略 NODE_ENV=development

javascript - 使用 Firebase 进行 Shopify 身份验证?