如何在React组件内部写入Apollo缓存,而不丢失“this”的上下文。

3
我在尝试从 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缓存正常运行。

1个回答

1
我最初因为分解第一个参数而失去了上下文,最终我选择了这个方案。
如果ROOT_QUERY对象上没有allAuthors,则会抛出错误,因此我将其添加到了返回语句中。
这种更新缓存的方式并不理想,传递给readQuery的默认参数是否应该防止抛出错误?
 updateCache(cache, { data: { createAuthor }, errors }) {
    if (errors || !cache.data.data.ROOT_QUERY.allAuthors) {
      return;
    }

    const query = ALL_AUTHORS;

    const { allAuthors } = cache.readQuery({
      query,
      defaults: {
        allAuthors: []
      }
    });

    const data = {
      allAuthors: allAuthors.concat([createAuthor])
    };

    cache.writeQuery({
      query,
      data
    });
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接