Apollo客户端TypeError:对象不起作用

时间:2020-08-10 11:14:49

标签: graphql react-apollo apollo-client apollo-boost

当前,我在查询Nexus GraphQL后端时遇到问题。在前端,我使用Apollo-boost(Apollo客户端)运行查询。我试图在一个简单的示例中从后端获取数据,但是它不起作用,而且我找不到问题。难道我做错了什么?这是我的代码:

TypeError:Object(...)不是函数

 353 | 
  354 | function useBaseQuery(query, options, lazy) {
  355 |     if (lazy === void 0) { lazy = false; }
> 356 |     var context = useContext(getApolloContext());
  357 |     var _a = useReducer(function (x) { return x + 1; }, 0), tick = _a[0], forceUpdate = _a[1];
  358 |     var updatedOptions = options ? __assign(__assign({}, options), { query: query }) : { query: query };
  359 |     var queryDataRef = useRef();



 400 | }
  401 | 
  402 | function useQuery(query, options) {
> 403 |     return useBaseQuery(query, options, false);
  404 | }
  405 | 
  406 | function useLazyQuery(query, options) {

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter } from 'react-router-dom';
import ApolloClient, { gql } from 'apollo-boost';
import { ApolloProvider, Query } from 'react-apollo';


const client = new ApolloClient({
   uri: 'http://localhost:4000/graphql',
});

const GET_ALL_GENRES = gql`
   {
      getAllGenres {
         genre_id
         title
      }
   }
`;

const ExchangeRates = () => (
   <Query query={GET_ALL_GENRES}>
      {({ loading, error, data }) => {
         if (loading) return <p>Loading...</p>;
         if (error) return <p>Error :(</p>;

         console.log(data);
         return <p>Succeed</p>;
      }}
   </Query>
);

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

这是一个已知问题吗? react-apollo gql, TypeError: Object(...) is not a function

我尝试了所有解决方案,但仍然无法正常工作。这些示例也来自官方文档。成功的唯一方法就是这种方法:

client
   .query({
      query: gql`
         {
            getAllGenres {
               genre_id
               title
            }
         }
      `,
   })
   .then((result) => console.log(result));

1 个答案:

答案 0 :(得分:0)

您正在使用Apollo Client 3,因此Query componentdeprecated。您应该使用useQuery而不是<Query/>

注意:不建议使用React Apollo的render prop组件。他们将继续收到错误修复,直到2020年3月,此后,阿波罗将不再维护它们。

您可以尝试以下方法:

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

const GET_ALL_GENRES = gql`
   query {
      getAllGenres {
         genre_id
         title
      }
   }
`;

const ExchangeRates = () => (
  const {data, loading, error } = useQuery(GET_ALL_GENRES)
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;
  console.log(data);
  return <p>Succeed</p>;
);

...