您的位置:首页 > 房产 > 家装 > Apollo学习笔记

Apollo学习笔记

2024/10/5 15:54:15 来源:https://blog.csdn.net/weixin_51621120/article/details/140019549  浏览:    关键词:Apollo学习笔记

安装依赖:

npm install @apollo/client graphql react

初始化Apollo Client

# 导入依赖库
const { ApolloClient, InMemoryCache, gql } = require('@apollo/client');# 创建ApolloClient实例
const client = new ApolloClient({uri: 'http://localhost:4000/',cache: new InMemoryCache(),
});

该例子中使用的uri和cache参数:

        uri:指定GraphQL的server地址

        cache:Apollo Client用来缓存查询结果

使用Apollo Client执行查询

# 执行查询
client.query({query: gql`query {hello}`,
}).then((result) => {console.log(result);
});

完整代码:

const { ApolloClient, InMemoryCache, gql } = require('@apollo/client');const client = new ApolloClient({uri: 'http://localhost:4000/',cache: new InMemoryCache(),
});client.query({query: gql`query {hello}`,
}).then((result) => {console.log(result);
});

将以上代码保存到test.js文件中,运行

node test.js{ data: { hello: 'Hello World!' }, loading: false, networkStatus: 7 }

一、查询

使用useQuery勾子获取数据

执行查询

useQuery勾子是用于Apollo应用程序中执行查询的主要API。在React组件中运行查询,调用并传递Graphql查询字符串。当组件渲染时,从Apollo Client返回对象,包含用于渲染UI、属性

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com