在不使用 hooks 的情况下,可以使用 Apollo Client 的 GraphQL,以下是一个示例解决方案:
npm install apollo-boost graphql
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: 'your_graphql_endpoint',
});
import React from 'react';
import { ApolloProvider, Query } from 'react-apollo';
import gql from 'graphql-tag';
const GET_DATA = gql`
query GetData {
// your query here
}
`;
class MyComponent extends React.Component {
render() {
return (
{({ loading, error, data }) => {
if (loading) return Loading...;
if (error) return Error :(;
// process and render data
return {/* render your data here */};
}}
);
}
}
export default MyComponent;
在这个示例中,我们使用了 react-apollo
包提供的 ApolloProvider
和 Query
组件。ApolloProvider
将 Apollo Client 实例传递给组件层级中的所有组件,Query
组件用于执行 GraphQL 查询,并处理加载、错误和数据返回的情况。
在 Query
组件的回调中,你可以根据加载状态、错误和数据来渲染组件。如果正在加载数据,可以显示加载中的消息。如果发生错误,可以显示错误消息。如果数据返回成功,可以处理数据并渲染组件。
这就是使用 Apollo Client 的 GraphQL 的解决方案,而不使用 hooks。您可以根据自己的需求修改和扩展代码。