graphql - 在 React 应用程序中,是优先于 client.query 执行查询?
问题描述
我正在开发一个 React 项目,其中使用 apollo 客户端执行如下查询:
const client = new ApolloClient({
link: link,
cache: new InMemoryCache(),
});
client.query({ query: gql`{ hello }` })
但我见过的大多数例子看起来像:
import gql from "graphql-tag";
import { Query } from "react-apollo";
const GET_DOGS = gql`
{
dogs {
id
breed
}
}
`;
const Dogs = ({ onDogSelected }) => (
<Query query={GET_DOGS}>
{({ loading, error, data }) => {
if (loading) return "Loading...";
if (error) return `Error! ${error.message}`;
return (
<select name="dog" onChange={onDogSelected}>
{data.dogs.map(dog => (
<option key={dog.id} value={dog.breed}>
{dog.breed}
</option>
))}
</select>
);
}}
</Query>
);
对于 React 应用程序,什么时候一种方法优于另一种?<Query>
语法总是首选吗?
解决方案
有query
直接在客户端调用的用例,但是是的,使用 Query 组件是模式。从文档:
当 React 挂载一个 Query 组件时,Apollo Client 会自动触发你的查询。如果您想延迟触发查询,直到用户执行操作(例如单击按钮),该怎么办?对于这种情况,我们希望使用 ApolloConsumer 组件并直接调用 client.query() 代替。... 以这种方式获取非常冗长,因此我们建议尽可能尝试使用 Query 组件!
Both the signature of the Query
component's render prop function and the value the query
call Promise resolves to are of the type ApolloQueryResult. However, there's some fine differences between the two. For example, using the Component means the loading
value will be updated multiple times to reflect the status of the query, while you don't get the same functionality when using the client directly.
Generally, using the client directly also means you'll need to persist the results in some other component's state as opposed to just using the values provided by the render props function.
If a query needs to be triggered manually, especially if the query results will not be persisted in state, it's perfectly fine to use the client directly. Otherwise, you're probably better off using the Query
component.
推荐阅读
- html - 如何在整个网站上指定一种语言?
- javascript - JavaScript 承诺中的日志输出显示 [object object]?
- apache-spark-sql - 从大量数据中仔细选择和检索一个
- html - React 如何创建组件保存历史导航路径
- azure - 如何从 azure devops chartimages api 中提取和绘制聊天
- jquery - 如何在全日历中获取从当前时间开始的事件?
- jenkins - 通过 groovy 脚本在 Jenkins 中编辑用户
- node.js - github-actions 如何在(生产)构建结果而不是开发模式上运行测试
- c++ - 成员函数的无效使用(你忘了 '()' 吗)
- hosting - Vercel - 重写到外部页面的路由