Apollo Graphql:避免在重新获取期间加载指示器
Posted
技术标签:
【中文标题】Apollo Graphql:避免在重新获取期间加载指示器【英文标题】:Apollo Graphql: Avoid loading indicator during refetch 【发布时间】:2018-03-26 07:17:34 【问题描述】:我有以下 apollo-graphql 客户端代码,其中我每 30 秒触发一次 graphql 查询并获取数据。
import React, Component from 'react';
import gql, graphql from 'react-apollo';
import _ from 'underscore';
class Test extends Component
render()
if (this.props.TestData.loading)
return <div>Loading...</div>
if (this.props.TestData.error && this.props.TestData.error !== null)
return <div>Error...</div>
// Iterate through the this.props.TestData.getTestData and build the Table of data here
return (
<table>
_.map(this.props.TestData.getTestData.testList, (test) =>
<tr>
<td>test.testName</td>
<td>test.status</td>
</tr>
)
</table>
);
const TestQuery = gql`
query TestQuery()
getTestData()
testList
testName
status
`;
const options = () => (
pollInterval: 30000,
);
const withTestData = graphql(TestQuery,
name: 'TestData',
options,
);
export default withTestData(Test);
我面临的问题是每 30 秒后我都会看到 Loading...
,因为查询被重新触发。我希望 Loading...
仅在页面启动时显示,此后它应该是平滑更新,我不想向用户显示 Loading...
指示器。不知道如何实现。
【问题讨论】:
【参考方案1】:我知道文档建议使用 data.loading
,但在大多数情况下,检查查询结果是否为空也同样有效:
// Should probably check this first. If you error out, usually your data will be
// undefined, which means putting this later would result in it never getting
// called. Also checking if it's not-null is a bit redundant :)
if (this.props.TestData.error) return <div>Error...</div>
// `testList` will only be undefined during the initial fetch
// or if the query errors out
if (!this.props.TestData.getTestData) return <div>Loading...</div>
// Render the component as normal
return <table>...</table>
请记住,GraphQL 可能会返回一些错误,但仍会返回数据。这意味着在生产环境中,您可能需要更强大的错误处理行为,如果出现任何错误,不一定会阻止页面呈现。
【讨论】:
太棒了,它奏效了。编辑您的代码,因为缺少否定并修改为指向正确的字段。以上是关于Apollo Graphql:避免在重新获取期间加载指示器的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Apollo 客户端 useQuery 钩子防止不必要的重新获取?
使用 Apollo 重新获取部分 GraphQL 查询的最佳实践?
ReactJS/Apollo/Graphql:使用 @skip 阻止 data.refetch 直到单击 onSubmit 但重新获取仍然可用
删除突变后不重新获取查询(Apollo Graphql & Nextjs)