【问题标题】:Trying to access apolloClient in getServerSideProps context尝试在 getServerSideProps 上下文中访问 apolloClient
【发布时间】:2020-09-16 09:45:34
【问题描述】:

我正在将 Next.js 9.3.5 与 Apollo 和 GraphQL 一起用于我正在进行的 SSR 项目。我已经实现了官方页面中提供的这个例子:

https://github.com/vercel/next.js/blob/canary/examples/with-apollo/lib/apollo.js

所以我的页面是这样的:

import { withApollo } from '../apollo/withApollo';

const Collections = (props) => {
   // ...
}

export const getServerSideProps = async ({ apolloClient }) => {
  console.log(apolloClient); // returns undefined

  return {
    props: {},
  };
};

export default withApollo()(Collections);

问题是apolloClientgetServerSideProps 中不可用。但是如果我使用getInitialProps,那么它就可以工作了。 Next.js 官方文档说我们应该使用getServerSideProps

如果您使用 Next.js 9.3 或更高版本,我们建议您使用 getStaticProps 或 getServerSideProps 而不是 getInitialProps。

有什么想法吗?

【问题讨论】:

  • 你在 NextPageContext 和 NextAppContext 中添加了apolloClient 吗?
  • 我必须手动操作吗?我对下一个还是很陌生。我怎么做?我似乎找不到任何关于它的信息。
  • 我从来没有做过 apollo + next 也没有,但是 context 对象默认没有 apolloClient 属性,看看这个 github.com/vercel/next.js/issues/9542#issuecomment-592187560
  • 想不通...我还尝试在withApollo 中将getInitialProps 替换为getServerSideProps,但也不能这样做:getServerSideProps can not be attached to a page's component
  • 嘿诺伯特,有什么解决办法吗?

标签: javascript next.js


【解决方案1】:

我只是使用它并在任何地方调用以访问 getServerSideProps 中的客户端

 export async function getStandaloneApolloClient() {
        const { ApolloClient, InMemoryCache, HttpLink } = await import(
            "@apollo/client"
            );
        return new ApolloClient({
            link: new HttpLink({
                uri: process.env.BASE_URL,
                fetch
            }),
            cache: new InMemoryCache()
        });
    }

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多