在ApolloConsumer的上下文中找不到“客户端”

时间:2019-05-01 00:23:59

标签: reactjs react-apollo next.js state-management apollo-link-state

我正在尝试实现react-apollo来存储我的本地状态,我可以使用client.writeData()向它们写入内容,但是当我尝试访问它们时,却不断收到错误消息

我尝试关注https://github.com/wesbos/Advanced-React/tree/master/finished-application/frontend。我也尝试实现了apollo-link-state,但一直抛出错误。

withData.js

import withApollo from "next-with-apollo";
import { ApolloClient } from "apollo-client";
import { createHttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
const cache = new InMemoryCache();

function createClient({ headers }) {
  return new ApolloClient({
    cache,
    link: new createHttpLink({
      uri: "http://localhost:4000/",
      request: operation => {
        operation.setContext({
          fetchOptions: {
            credentials: "same-origin"
          },
          headers: {
            "Content-Type": "application/json"
          }
        });
      }
    }),
    clientState: {
      resolvers: {
        Query: {
          getLocalData: (_, { text }, { cache }) => {
            const query = gql`
              query getLocalData {
                loading @client
              }
            `;
            const previous = cache.readQuery({ query });
            return previous.loading;
          }
        },
        Muatation: {
          toggleLoading: (_, { text }, { cache }) => {
            const query = gql`
              query getLocalData {
                loading @client
              }
            `;
            var previous = cache.readQuery({ query });
            cache.writeData({ data: { loading: !previous.loading } });
            return null;
          }
        }
      },
      defaults: {
        loading: true,
      },
      typeDefs: {}
    }
  });
}

export default withApollo(createClient);

_app.js

import App, { Container } from 'next/app';
import Page from '../components/Page';
import { ApolloProvider } from 'react-apollo';
import withData from '../lib/withData';

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }
    // this exposes the query to the user
    pageProps.query = ctx.query;
    return { pageProps };
  }
  render() {
    const { Component, apollo, pageProps } = this.props;

    return (
      <Container>
        <ApolloProvider client={apollo}>
          <Page>
            <Component {...pageProps} />
          </Page>
        </ApolloProvider>
      </Container>
    );
  }
}

export default withData(MyApp);

我希望高效运行 但实际输出是:在ApolloConsumer的上下文中找不到“客户端”。将根组件包装在

0 个答案:

没有答案