阅读查询阿波罗查询抛出不变错误
我正在尝试从Apollo中读取一些缓存的信息,但似乎受到以下错误的打击:
不变式违规:在未定义的对象上找不到字段Posts({“ id”:“ 5eb2db3b99cacd7be0e65541”,“ startingDate”:“ 2020-05-01”})。我的查询看起来像这样:
query Post($id: ID!, $startingDate: String!) {
Post(id: $id, startingDate: $startingDate) {
id
title
description
author {
id
name
picture
followers
}
}
}
我也可以看到对象也存在于缓存中
我正在调用的代码查询行导致错误为const foo = this.props.apolloClient.readQuery({query: postQuery, variables: {id: '5eb2db3b99cacd7be0e65541', startingDate: "2020-05-01"}});
。另外,我在这里查看了文档:https://www.apollographql.com/docs/react/v2.4/advanced/caching/#readquery。对这里缺少什么的想法?
还遇到了以下Github问题:
没有一个可以清楚地回答我所面临的问题。
我的组件设置如下:
/**
* @flow
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'react-apollo';
// Queries
import postQuery from './queries/post-query.gql';
import withApollo from 'components/with-apollo';
class PostWidget extends Component {
render() {
const { data } = this.props;
const foo = this.props.apolloClient.readQuery({query: postQuery, variables: {id: '5eb2db3b99cacd7be0e65541', startingDate: "2020-05-01"}});
// ^^ error is thrown at this point.
// expectation is if I console.log(foo) it returns the cached object
return (
<section>
<div>Stripped Content</div>
</section>
);
}
}
class PostWithDates extends Component {
state = {
monthlyQueryDate: new Date(),
}
render() {
const { targetId, targetType } = this.props;
const Component = graphql(postQuery, {
options: ({ targetId }) => ({
variables: { id: targetId, startingDate: this.state.monthlyQueryDate },
fetchPolicy: 'cache-and-network'
})
})(PostWidget);
return <Component
{...this.props}
targetType={targetType}
/>;
}
}
export default withApollo(PostWithDates);
function createApolloClient() {
const hostUrl = Reactor.evaluate(Sessions.getters.hostUrl) || '';
return new ApolloClient({
uri: `${Config.api.host}/graphql`,
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Parent-URL': hostUrl
}
});
}
const withApollo = (WrappedComponent: ClassComponent<*, *, *>) => (props: Object) => (
<ApolloProvider client={createApolloClient()}>
<WrappedComponent {...props} client={createApolloClient() } />
</ApolloProvider>
);
export default withApollo;
所以看来我之所以遇到这个问题,是因为我没有打电话给client.query({query: postQuery, variables: {id: "5ec947a999cacdd4b52f56b4", startingDate: "2020-06-01"}})
。调用此方法并then读取查询将返回缓存的对象。这对我来说没有任何意义,因为我通过react-apollo graphql
函数执行查询的方式。我的问题确实是如何在不调用#client.query()
的情况下读取缓存的值。
键是时间-访问数据的时刻。
在第一个渲染(当数据尚未到达时)显然不包含此数据。通常,渲染未就绪的数据时要注意条件,例如
if(!this.props.data) return <Loading/>;
您应该以相同的方式来保护访问缓存,例如
const { data } = this.props; const foo = data ? this.props.apolloClient.readQuery({query: postQuery, variables: {id: '5eb2db3b99cacd7be0e65541', startingDate: "2020-05-01"}}) : null;