TypeError: Cannot read properties of undefined (reading 'watchQuery')

TypeError: Cannot read properties of undefined (reading 'watchQuery')

我尝试从 React 应用建立 graphql 连接。 我的 index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ApolloProvider } from '@apollo/client'
import { createClient } from 'graphql-ws';

const client = createClient({
  url: '<some url>',
  connectionParams: {
    authToken: '<some token>',
  },
});

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
  ,
  document.getElementById('root')
);

我的App.js:

import { gql, useSubscription, useQuery } from '@apollo/client'


const QUERY = gql`query SomeName{
  test_tablesList {
    items {
      id
      num
    }
  }
}`;


function App() {
  const { data, loading } = useQuery(QUERY);
  return (
    <h1>Hi there</h1>
  );
}

export default App;

当我 运行 它控制台争辩说:

useQuery.ts:31 未捕获类型错误:无法读取未定义的属性(读取 'watchQuery') 在 useQuery (useQuery.ts:31:1) 在应用 (App.js:25:1)

react-dom.development.js:18525 组件出现以上错误:

at App (http://localhost:3000/main.cf5965058b2b7700d166.hot-update.js:48:63)
at ApolloProvider (http://localhost:3000/static/js/bundle.js:51749:19)

我做错了什么?

我的错误在这里 - import { createClient } from 'graphql-ws'; 我不得不从阿波罗客户那里拿走它。

您可以试试这个解决方案:

  • 在 src 目录中创建一个名为 ApolloClient.js
  • 的文件
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
const client = new ApolloClient({
  link: new HttpLink({
    uri: "PUT-HERE-URL-TO-GRAPHQL-END-POINT",
    headers: {
      // PUT-HERE-ANY-HEADER-VARS-IF-EXISTS
    },
  }),
  cache: new InMemoryCache(),
});
export default client;

  • 在你的index.js
  • 里面
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { ApolloProvider } from "@apollo/client";
import client from "./ApolloClient";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>
);

  • 最后在你的组件中调用 graphql 查询 App.js
import { gql, useSubscription, useQuery } from '@apollo/client'


const QUERY = gql`query SomeName{
  test_tablesList {
    items {
      id
      num
    }
  }
}`;


function App() {
  const { data, loading } = useQuery(QUERY);
  return (
    <h1>Hi there</h1>
  );
}

export default App;

Apollo client docs