我有graphql查询如下:
<Query query={GET_COMPANY_ADDRESSES} variables={{companyId: session.company.id}} notifyOnNetworkStatusChange={true} fetchPolicy={'cache-and-network'}>
{({loading, error, refetch, data}) => {
if (loading) return <LoadingIndicator/>;
if (error) return <ErrorIndicator description={error.message}/>;
const address = data.companyAddresses[1];
return (
<React.Fragment>
<CollapsiblePanel title="Add slot">
<SlotForm address={address} toggleSlotForm={this.toggleSlotForm.bind(this)} refetch={refetch}/>
</CollapsiblePanel>
</React.Fragment>
)
}}
</Query>
我在初始加载时显示有loading indicator
。它工作正常。但我在<SlotForm />
组件中有表单,我可以在其中添加记录到数据库。表格的提交功能如下:
handleSaveSlot({address}, data) {
const slot = {
...data,
address: address.id
};
return client.mutate({
variables: {input: slot},
mutation: ADD_NEW_SLOT,
})
.then(result => {
if (result.data.createSlot.ok) {
this.props.refetch();
this.setState({hasError: false, errorMessage: "", saved: true, slot: initialSlot()}, () => {
setTimeout(() => this.props.toggleSlotForm(false), 3000)
});
}
})
.catch(error => {
let error_msg = error.message.replace("GraphQL error: ", '');
this.setState({hasError: true, saved: false, errorMessage: error_msg});
throw(error_msg);
});
}
在.then
回应后,我用this.props.refetch();
重新获取数据。但是当执行重新获取时,我会在屏幕上更新数据之前再次获取加载指示符。
我想避免这种情况,每次添加新记录时我都不想显示loading indicator
。我只想在初始加载时显示它。
每当我获取数据时,我想“在后台”执行此操作而不显示加载指示符。
知道怎么做吗?
改变你的条件就足够了:
if (loading && !data.companyAddresses) {
return <LoadingIndicator/>;
}
data.companyAddresses
将在您的初始查询完成之前未定义,但即使您触发重新提取也应定义。
如果可能,您还应该考虑将update
选项与Mutation
组件一起使用,而不是重新查询查询。在发生突变后手动更新缓存通常比重新获取更快,因为它更快并减少了网络负载。有关详细信息,请参阅the docs。