当前位置: 首页 > 知识库问答 >
问题:

React Apollo Client useQuery Hook gql未捕获类型错误:(...)不是函数

景震博
2023-03-14

因此,我想使用Apollo客户端react钩子“usequery”查询运行Apollo服务器的graphql后端。

但是定义的查询常量将返回一个错误,它是:uncatched typeerror:(...)不是函数,因此页面根本不呈现。

我的ApolloClient和提供程序设置如下:

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { ApolloLink, from } from 'apollo-link';
import { ApolloProvider } from 'react-apollo';
import { createUploadLink } from 'apollo-upload-client';

import 'bootstrap/dist/css/bootstrap.min.css';
import App from './components/App';
import './index.css';

const uploadLink = createUploadLink({ uri: process.env.REACT_APP_API_URL });
const httpLink = new HttpLink({
  uri: process.env.REACT_APP_API_URL,
  credentials: 'same-origin'
});
const cache = new InMemoryCache();

const client = new ApolloClient({
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors)
        graphQLErrors.forEach(({ message, locations, path }) =>
          console.log(
            `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
          )
        );
      if (networkError) console.log(`[Network error]: ${networkError}`);
    }),
    httpLink,
    uploadLink
  ]),
  cache,
  uri: process.env.REACT_APP_API_URL
});

render(
  <ApolloProvider client={client}>
    <Router>
      <App />
    </Router>
  </ApolloProvider>,
  document.getElementById('app')
);
import React, { Component } from 'react';
// import GameForm from './gameform';
import GameRules from './gamerules';
// import PropTypes from 'prop-types';

import { gql } from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';

class GamePage extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);

    this.GET_ALL_PLAYERS = gql`
      query allPlayers {
        allPlayers {
          id
          name
          nickname
        }
      }
    `;
  }
  state = { selectedGame: 'X01' };

  componentDidMount() {
    // const players = this.props;
    // players.loadPlayers().catch(err => {
    //   alert('Loading players failed. ' + err);
    // });

    const { loading, error, data } = useQuery(this.GET_ALL_PLAYERS);

    if (loading) console.log('Loading...');
    if (error) console.log(`Error! ${error.message}`);
    console.log(data);
  }

  handleSubmit = gameObject => {
    console.log(gameObject);
    // this.props.createGame(gameObject);
  };

  handleGameChange = game => {
    this.setState({
      selectedGame: game
    });
  };

  render() {
    const styles = {
      margin: '20px'
    };

    return (
      <div className="container-fluid">
        <div className="row">
          <div className="col-md-6">
            <h2 style={styles}>Game Setup</h2>
            {/* <GameForm
              players={this.props.players}
              onSubmit={this.handleSubmit}
              onGameChange={this.handleGameChange}
            /> */}
          </div>
          <div className="col-md-6">
            <h2 style={styles}>Game Rules</h2>
            <GameRules game={this.state.selectedGame} />
          </div>
        </div>
      </div>
    );
  }
}

// GamePage.propTypes = {
//   players: PropTypes.array,
//   games: PropTypes.array,
//   createGame: PropTypes.func.isRequired
// };

export default GamePage;

当加载应用程序时,它会给我上面提到的错误。我在2小时内跟踪了我能找到的每一个教程,googeling和YouTubing。但我自己解决不了。此外,后端工作得很好。使用ApolloServer的Webserver测试工具对其进行了测试。

有问题的部分是这样的:

this.GET_ALL_PLAYERS = gql`
  query playersList {
    allPlayers {
      id
      name
      nickname
    }
  }
`;

所以任何帮助都将不胜感激。谢谢

编辑:将{gql}导入更改为gql后出现新错误

共有1个答案

姬国安
2023-03-14

如果没有看到完整的错误(包括跟踪),很难确定,但我怀疑您没有正确地从导入apollo-link模块确实导出了一个名为apollolink的类,但是这个类没有名为from的静态方法。相反,您正在寻找来自同一模块的另一个命名导出:

import { from } from 'apollo-link'

另外,请注意react-apollo-hooks模块现在不推荐使用,因为钩子API现在是react-apollo的一部分。您应该升级react-apollo,并且只为钩子和任何遗留组件使用单个ApolloProvider。

编辑:

import gql from 'graphql-tag'

 类似资料: