要在Apollo Server和React中处理对象数组和订阅,您可以按照以下步骤进行操作:
User
,其中包含一个字段name
和一个字段posts
(表示用户的帖子数组)。const { gql } = require('apollo-server');
const typeDefs = gql`
type User {
name: String
posts: [Post]
}
type Post {
title: String
content: String
}
type Query {
user: User
}
type Subscription {
postAdded: Post
}
`;
user
查询和postAdded
订阅。const { PubSub } = require('apollo-server');
const pubsub = new PubSub();
const resolvers = {
Query: {
user: () => ({
name: 'John Doe',
posts: []
})
},
Subscription: {
postAdded: {
subscribe: () => pubsub.asyncIterator('POST_ADDED')
}
}
};
PubSub
类来实现订阅和发布。const { ApolloServer } = require('apollo-server');
const server = new ApolloServer({
typeDefs,
resolvers
});
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
ApolloClient
来连接到Apollo Server,并使用useSubscription
钩子来订阅postAdded
订阅。import { ApolloClient, InMemoryCache, ApolloProvider, useSubscription, gql } from '@apollo/client';
import React from 'react';
const client = new ApolloClient({
uri: 'http://localhost:4000/',
cache: new InMemoryCache()
});
const POST_ADDED = gql`
subscription {
postAdded {
title
content
}
}
`;
function App() {
const { data, loading } = useSubscription(POST_ADDED);
if (loading) {
return Loading...
;
}
return (
{data && (
{data.postAdded.title}
{data.postAdded.content}
)}
);
}
ReactDOM.render(
,
document.getElementById('root')
);
useQuery
钩子来获取用户数据。import { useQuery, gql } from '@apollo/client';
import React from 'react';
const GET_USER = gql`
query {
user {
name
posts {
title
content
}
}
}
`;
function App() {
const { data, loading } = useQuery(GET_USER);
if (loading) {
return Loading...
;
}
return (
{data.user.name}
Posts:
{data.user.posts.map((post, index) => (
{post.title}
{post.content}
))}
);
}
ReactDOM.render(
,
document.getElementById('root')
);
这些是处理Apollo Server和React中的对象数组和发布的基本步骤和示例代码。您可以根据自己的需求进行调整和扩展。