reactjs 是否可以将Graphql查询与React类组件一起使用?

mzillmmw  于 2022-12-22  发布在  React
关注(0)|答案(3)|浏览(132)

我需要把这个组件转换成一个类组件,我怎样才能替换useQuery钩子呢?

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

const getBooks = gql`
  {
    books {
      name
    }
  }
`;

function BookList() {
  const {data} = useQuery(getBooks);
      
  console.log(data);
  return (
    <div>
      <ul id="book-list">
        {data.books.map(book => (
          <li key={book.id}>{book.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default BookList;
kxkpmulp

kxkpmulp1#

溶液-1

您可以使用如Mark所述的高阶元件,并且可以通过制作如下元件来实现:

const withHook = (Component) => {
      return WrappedComponent = (props) => {
        const someHookValue = useSomeHook();
        return <Component {...props} someHookValue={someHookValue} />;
       }
    }

你可以这样使用它:

class Foo extends React.Component {
  render(){
    const { someHookValue } = this.props;
    return <div>{someHookValue}</div>;
  }
}

export default withHook(Foo);

Source用于上述代码段。
溶液-2
如果你对使用apollo克林特不感兴趣,你可以使用AXIOS或者普通的fetch,或者使用graphql-request库,从你的服务器上获取数据:

import { request, gql } from 'graphql-request';

const getBooks = gql`
  {
    books {
      name
    }
  }
`;

function BookList() {
  request('https://<server-link>', getBooks).then((data) => (
    <div>
      <ul id="book-list">
        {data.books.map(book => (
          <li key={book.id}>{book.name}</li>
        ))}
      </ul>
    </div>
  ));
      
}

export default BookList;
eqoofvh9

eqoofvh92#

https://softchris.github.io/pages/graphql-apollo-client.html#query
在这里你可以找到答案。这里有一种不用useQuery进行查询的方法。
我在我的项目中试过了,效果很好。

sqxo8psd

sqxo8psd3#

我也遇到过同样的情况,以下是对我有效的解决方案:

package.json部分视图

"dependencies": {
  "@apollo/client": "^3.6.9",
  "@apollo/react-components": "^4.0.0",
  "@testing-library/jest-dom": "^5.14.1",
  "@testing-library/react": "^11.2.7",
  "@testing-library/user-event": "^12.8.3",
  "graphql": "^16.5.0",
  "react": "^17.0.2",
  "react-dom": "^17.0.2",
  "react-scripts": "4.0.3",
  "web-vitals": "^1.1.2"
},

书单组件

import React, { Component } from "react";
import { graphql } from "@apollo/client/react/hoc";
import { gql } from "@apollo/client";        
//--------------------------------------------------------`

const GETBOOKS = gql`
  {
    books {
      title
      id
    }
  }
`;

class BookList extends Component {
  displayBooks = () => {
    let data = this.props.data;
    if (data.loading) {
      return <div>Loading Books ...</div>;
    } else {
      return data.books.map((book) => {
        return <li key={book.id}>{book.title}</li>;
      });
    }
  };

  render() {
    console.log(this.props);
    return (
      <div>
        <ul id="book-list">{this.displayBooks()}</ul>
      </div>
    );
  }
}
export default graphql(GETBOOKS)(BookList);
// use grahql to bind getBookQuery to BookList component

更多细节请参见我的github repo

https://github.com/danielOuattara/GraphQL_TheNetNinja

相关问题