@apollo/client、apollo-client与apollo-boost的区别及React完整示例咨询
Hey there! Let's clear up the confusion around Apollo Client, Apollo Boost, and get you a complete React example using the modern @apollo/client package.
Apollo Client vs. Apollo Boost vs. Legacy Apollo Client: Key Differences
- @apollo/client: This is the modern, all-in-one core package recommended by Apollo right now. It combines the functionality of the old
apollo-client,apollo-link,in-memory-cache, and other related packages into a single dependency. It gives you full control over advanced configurations (custom links, cache strategies, auth headers, etc.)—exactly what you're importing with classes likeApolloClientandInMemoryCache. - apollo-boost: A deprecated "batteries-included" wrapper for Apollo Client designed for zero-config quick setup. It hid underlying complexity but lacked flexibility for custom use cases. Since
@apollo/clientnow includes all its features (and more), Apollo no longer maintains this package. Your second import example uses this outdated package. - Legacy apollo-client: The old standalone core package that required manual installation of companion packages like
apollo-link-http,in-memory-cache, etc. It's been fully absorbed into@apollo/clientand is no longer supported.
Complete @apollo/client + React Example
Step 1: Install Dependencies
First, install the required packages:
npm install @apollo/client graphql react # Or with yarn: yarn add @apollo/client graphql react
Step 2: Set Up the Apollo Client
Create a dedicated file for your client configuration (e.g., src/apollo/client.js):
import { ApolloClient, InMemoryCache, createHttpLink, defaultDataIdFromObject } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; // 1. Create a basic HTTP link pointing to your GraphQL API const httpLink = createHttpLink({ uri: 'https://your-graphql-api-url.com/graphql', // Replace with your API endpoint }); // 2. Add auth headers (optional but common) const authLink = setContext((_, { headers }) => { // Fetch token from localStorage (adjust based on your auth flow) const token = localStorage.getItem('authToken'); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : '', }, }; }); // 3. Combine links and initialize the client const client = new ApolloClient({ // Use the combined auth + HTTP link link: authLink.concat(httpLink), cache: new InMemoryCache({ // Customize cache ID generation (optional) dataIdFromObject: (object) => { switch (object.__typename) { case 'User': return `User:${object.id}`; case 'Post': return `Post:${object.slug}`; default: return defaultDataIdFromObject(object); } }, }), }); export default client;
Step 3: Wrap Your App with ApolloProvider
In your root component (e.g., src/App.js), wrap your entire app with ApolloProvider to make the client available to all components:
import { ApolloProvider } from '@apollo/client/react'; import client from './apollo/client'; import PostList from './components/PostList'; import CreatePost from './components/CreatePost'; function App() { return ( <ApolloProvider client={client}> <div className="App"> <h1>My Apollo + React Blog</h1> <CreatePost /> <PostList /> </div> </ApolloProvider> ); } export default App;
Step 4: Build a Query Component
Create a component that fetches data with useQuery (e.g., src/components/PostList.js):
import { useQuery, gql } from '@apollo/client'; // Define your GraphQL query const GET_POSTS = gql` query GetPosts { posts { id title content author { name } } } `; function PostList() { const { loading, error, data } = useQuery(GET_POSTS); if (loading) return <p>Loading posts...</p>; if (error) return <p>Oops! Error: {error.message}</p>; return ( <div className="post-list"> <h2>Latest Posts</h2> <ul> {data.posts.map(post => ( <li key={post.id}> <h3>{post.title}</h3> <p><em>By {post.author.name}</em></p> <p>{post.content}</p> </li> ))} </ul> </div> ); } export default PostList;
Step 5: Build a Mutation Component
Add a component to create data with useMutation (e.g., src/components/CreatePost.js):
import { useMutation, gql } from '@apollo/client'; import { useState } from 'react'; import { GET_POSTS } from './PostList'; // Define your GraphQL mutation const CREATE_POST = gql` mutation CreatePost($title: String!, $content: String!) { createPost(title: $title, content: $content) { id title content author { name } } } `; function CreatePost() { const [title, setTitle] = useState(''); const [content, setContent] = useState(''); // Initialize the mutation, with cache update to refresh the post list const [createPost, { loading, error }] = useMutation(CREATE_POST, { update(cache, { data: { createPost } }) { const { posts } = cache.readQuery({ query: GET_POSTS }); cache.writeQuery({ query: GET_POSTS, data: { posts: [...posts, createPost] }, }); }, }); const handleSubmit = (e) => { e.preventDefault(); createPost({ variables: { title, content } }); // Reset form setTitle(''); setContent(''); }; return ( <form onSubmit={handleSubmit} className="create-post-form"> <h2>Add a New Post</h2> <div> <label>Title:</label> <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} required /> </div> <div> <label>Content:</label> <textarea value={content} onChange={(e) => setContent(e.target.value)} required /> </div> <button type="submit" disabled={loading}> {loading ? 'Creating...' : 'Publish Post'} </button> {error && <p className="error">Error: {error.message}</p>} </form> ); } export default CreatePost;
内容的提问来源于stack exchange,提问作者apps
相关产品推荐
相关产品推荐

