Apollo Client的主要优点包括:
- 简化数据获取:通过使用
useQuery或useLazyQuery钩子,可以轻松地进行GraphQL查询,并自动管理查询结果的缓存。例如,如果我们需要从服务器获取用户信息,可以这样编写:
import { useQuery } from '@apollo/client';
import gql from 'graphql-tag';
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
`;
function User(props) {
const { loading, error, data } = useQuery(GET_USER, {
variables: { id: props.userId },
});
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <p>Hello, {data.user.name}</p>;
}
- 变更管理:通过使用
useMutation钩子,可以执行GraphQL变更新以修改服务器上的数据。变更不仅能够更新服务器数据,还可以通过update参数手动更新缓存中的数据,确保UI的一致性和响应性。例如,更新用户的电子邮件地址:
import { useMutation } from '@apollo/client';
import gql from 'graphql-tag';
const UPDATE_USER_EMAIL = gql`
mutation UpdateUserEmail($id: ID!, $email: String!) {
updateUser(id: $id, email: $email) {
id
email
}
}
`;
function UpdateEmail(props) {
const [updateUserEmail, { loading, error }] = useMutation(UPDATE_USER_EMAIL);
const handleSubmit = () => {
updateUserEmail({
variables: { id: props.userId, email: 'newemail@example.com' },
optimisticResponse: {
updateUser: {
__typename: 'User',
id: props.userId,
email: 'newemail@example.com',
},
},
});
};
return (
<div>
<button onClick={handleSubmit} disabled={loading}>Update Email</button>
{error && <p>Error: {error.message}</p>}
</div>
);
}
- 灵活的缓存策略:Apollo Client提供了高级缓存功能,包括自动缓存和可自定义的缓存策略。这有助于减少不必要的网络请求,提高应用性能。例如,可以通过
cache.writeQuery手动写入缓存:
import { useQuery, useMutation, gql } from '@apollo/client';
const GET_POST = gql`
query GetPost($id: ID!) {
post(id: $id) {
id
title
content
}
}
`;
const UPDATE_POST = gql`
mutation UpdatePost($id: ID!, $title: String!, $content: String!) {
updatePost(id: $id, title: $title, content: $content) {
id
title
content
}
}
`;
function PostEditor(props) {
const { data } = useQuery(GET_POST, {
variables: { id: props.postId },
});
const [updatePost] = useMutation(UPDATE_POST, {
onCompleted: (data) => {
props.cache.writeQuery({
query: GET_POST,
variables: { id: props.postId },
data: { post: data.updatePost },
});
},
});
return (
<div>
<input value={data.post.title} onChange={(e) => updatePost({ variables: { id: props.postId, title: e.target.value, content: data.post.content } })} />
<textarea value={data.post.content} onChange={(e) => updatePost({ variables: { id: props.postId, title: data.post.title, content: e.target.value } })} />
</div>
);
}