您好,登錄后才能下訂單哦!
在React中使用GraphQL訂閱實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)更新的步驟如下:
apollo-client
和@apollo/react-hooks
來與GraphQL服務(wù)端通信,以及subscriptions-transport-ws
用于訂閱實(shí)時(shí)更新。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
鉤子來訂閱數(shù)據(jù)更新。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訂閱實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)更新了。當(dāng)GraphQL服務(wù)端的數(shù)據(jù)發(fā)生變化時(shí),React組件會(huì)自動(dòng)更新顯示最新的數(shù)據(jù)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。