在React中使用Apollo GraphQL的高阶组件(HOC)将查询作为属性函数传递,可以按照以下步骤进行:
react-apollo
和@apollo/client
。你可以使用以下命令安装它们:npm install react-apollo @apollo/client
import React from 'react';
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
import { graphql } from '@apollo/react-hoc';
import gql from 'graphql-tag';
ApolloProvider
组件中:const client = new ApolloClient({
uri: 'YOUR_GRAPHQL_API_ENDPOINT',
cache: new InMemoryCache(),
});
const App = () => (
{/* Your components */}
);
graphql
高阶组件中:const GET_DATA = gql`
query GetData {
data {
id
name
}
}
`;
const MyComponent = (props) => {
// Access the data returned by the query
const { data } = props;
// Render your component
return (
{data.loading ? (
Loading...
) : (
data.data.map((item) => (
{item.name}
))
)}
);
};
const MyComponentWithData = graphql(GET_DATA)(MyComponent);
在上面的代码中,我们使用gql
函数创建了一个GraphQL查询,然后将其作为参数传递给graphql
高阶组件。这个高阶组件将查询结果作为data
属性传递给包装的组件。
ApolloProvider
中渲染你的组件:const App = () => (
);
现在,MyComponent
组件将接收到来自GraphQL查询的数据作为data
属性。你可以根据需要在组件中使用这些数据。如果查询正在加载,你可以显示一个加载中的提示。一旦查询完成,你可以显示数据。
请记住,你需要将YOUR_GRAPHQL_API_ENDPOINT
替换为你的实际GraphQL API的端点。