在React中使用GraphQL订阅实现实时数据更新的步骤如下:
apollo-client
和@apollo/react-hooks
来与GraphQL服务端通信,以及subscriptions-transport-ws
用于订阅实时更新。npm install @apollo/client @apollo/react-hooks subscriptions-transport-ws
import { ApolloClient, InMemoryCache, createHttpLink, split } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';
import { ApolloProvider } from '@apollo/react-hooks';
const httpLink = createHttpLink({
uri: 'http://your-graphql-server-url',
});
const wsLink = new WebSocketLink({
uri: 'ws://your-graphql-server-url',
options: {
reconnect: true
}
});
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
},
wsLink,
httpLink,
);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const App = () => (
<ApolloProvider client={client}>
<YourComponent />
</ApolloProvider>
);
useSubscription
钩子来订阅数据更新。import { useSubscription } from '@apollo/react-hooks';
import { gql } from '@apollo/client';
const SUBSCRIPTION_QUERY = gql`
subscription {
yourSubscription {
id
data
}
}
`;
const YourComponent = () => {
const { data, loading } = useSubscription(SUBSCRIPTION_QUERY);
if (loading) return <div>Loading...</div>;
return (
<div>
<p>ID: {data.yourSubscription.id}</p>
<p>Data: {data.yourSubscription.data}</p>
</div>
);
};
通过以上步骤,就可以在React中使用GraphQL订阅实现实时数据更新了。当GraphQL服务端的数据发生变化时,React组件会自动更新显示最新的数据。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。