这通常是因为 Apollo 客户端没有正确配置或未正确设置,可以通过以下代码示例来解决:
import {ApolloClient, InMemoryCache, ApolloProvider} from '@apollo/client';
import {WebSocketLink} from '@apollo/client/link/ws';
const link = new WebSocketLink({
uri: 'ws://localhost:4000/graphql',
options: {
reconnect: true,
lazy: true,
},
});
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
ReactDOM.render(
,
document.getElementById('root')
);
import {useSubscription, gql} from '@apollo/client';
const MY_SUBSCRIPTION = gql`
subscription MySubscription($param1: String!, $param2: Int!) {
...
}
`;
function MyComponent(props) {
const {data, loading, error} = useSubscription(MY_SUBSCRIPTION, {
variables: {param1: 'value1', param2: 2},
});
...
}
确保在使用订阅时,提供正确的参数。