我在尝试从
依赖项如下:
react
组件中读取 apollo 缓存时遇到了问题,即使变异可以正常工作并写入我的服务器并返回数据,但当传递给我的更新函数时,它似乎在 inMemoryCache.js
中丢失了上下文。依赖项如下:
- "apollo-cache-inmemory": "^1.2.5"
- "react-apollo": "^2.1.4"
- "apollo-boost": "^0.1.7"
TypeError: Cannot read property 'read' of undefined at ./node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.readQuery
import React, { Component } from "react";
import { graphql } from "react-apollo";
import trim from "lodash/trim";
import AuthorForm from '../components/author-form';
import ALL_AUTHORS from "../graphql/getPosts.query";
import CREATE_AUTHOR from "../graphql/createAuthor.mutation";
class CreateAuthor extends Component {
state = {
errors: false
};
onSubmit(event) {
event.preventDefault();
const form = new FormData(event.target);
const data = {
firstName: form.get("firstName"),
lastName: form.get("lastName")
};
if (!data.firstName || !data.lastName) {
return this.setState({ errors: true });
}
this.create({
firstName: trim(data.firstName),
lastName: trim(data.lastName)
});
}
async create(variables) {
const { createAuthor } = this.props;
this.setState({ errors: false });
try {
await createAuthor({
variables,
update: (cache, data) => this.updateCache(cache, data)
})
} catch (e) {
this.setState({ errors: true })
}
}
updateCache({ readQuery, writeQuery }, { data: { createAuthor }, errors }) {
if (errors) {
return;
}
const { allAuthors } = readQuery({
query: ALL_AUTHORS,
defaults: {
allAuthors: []
}
});
/*eslint-disable*/ console.log(allAuthors);
}
render() {
return (
<div>
<AuthorForm onSubmit={this.onSubmit.bind(this)}/>
<OnError/>
</div>
);
}
}
export default graphql(CREATE_AUTHOR, { name: "createAuthor" })(CreateAuthor);
这与我将其绑定到onSubmit按钮有关吗?如果是,那么正确的方法是什么,可以将函数附加到元素上,而不会失去组件内部的上下文,并且仍然允许Apollo缓存正常运行。