Apollo Client 缓存和 Next.js 结合使用的解决方案通常包括以下步骤:
安装所需的依赖:
npm install apollo-boost graphql apollo-client apollo-cache-inmemory apollo-link-http isomorphic-unfetch next-with-apollo
创建一个 Apollo Client 实例,并添加缓存配置:
// apollo.js
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
const cache = new InMemoryCache();
const link = new HttpLink({
uri: 'http://localhost:4000/graphql', // 根据实际情况修改 GraphQL API 的 URL
fetch: typeof window !== 'undefined' ? window.fetch : global.fetch,
});
const client = new ApolloClient({
cache,
link,
});
export default client;
在 Next.js 页面中使用 Apollo Client:
// pages/index.js
import { withApollo } from 'next-with-apollo';
import { gql } from 'apollo-boost';
const GET_USERS = gql`
query getUsers {
users {
id
name
}
}
`;
const IndexPage = ({ data }) => {
const { loading, error, users } = data;
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
Users
{users.map((user) => (
{user.name}
))}
);
};
IndexPage.getInitialProps = async ({ apolloClient }) => {
const { data } = await apolloClient.query({ query: GET_USERS });
return { data };
};
export default withApollo(IndexPage);
在 _app.js
文件中将 Apollo Client 添加到 Next.js 应用中:
// _app.js
import App from 'next/app';
import { ApolloProvider } from '@apollo/react-hooks';
import withApollo from '../apollo';
class MyApp extends App {
render() {
const { Component, pageProps, apolloClient } = this.props;
return (
);
}
}
export default withApollo(MyApp);
通过上述步骤,你就可以在 Next.js 应用中使用 Apollo Client 缓存了。在页面加载时,IndexPage
组件会通过 getInitialProps
方法从 GraphQL API 获取数据,并将数据传递给组件进行渲染。在后续的页面导航中,Apollo Client 会使用缓存数据,以提高性能和减少网络请求。