【问题标题】:Can't Store Result of GraphQL Query - Always undefined无法存储 GraphQL 查询的结果 - 始终未定义
【发布时间】:2019-06-05 16:37:23
【问题描述】:

我正在查询并且已经记录了结果。一切正常,但是当我想继续处理结果时,它总是“未定义”(参见第二次日志记录)。 我确定我在这里错过了一些明显的东西,但我真的很想得到你的帮助:)

render() {
let saved;
this.props.apolloClient
  .watchQuery<Query>({
    query: gql`
      query($id: ID!) {
        element(id: $id) {
          children {
            ... on TextNote {
              name
              description
              type
            }
          }
        }
      }
    `,
    variables: { id: 0 }
  })
  .subscribe(({ data: { element: { children } } }) => {
    console.log(children); // this is the wanted result
    saved = children;
  });

console.log("save");
console.log(saved);   // this is undefined for some reason

【问题讨论】:

    标签: javascript node.js reactjs typescript graphql


    【解决方案1】:

    如果children 给你正确的结果,你能不能只将你的变量saved 分配给你的this.props.apolloClient 函数并在subscribe 调用中返回子级?

    类似:

     render() {
      const saved = this.props.apolloClient
      .watchQuery<Query>({
        query: gql`
          query($id: ID!) {
            element(id: $id) {
              children {
                ... on TextNote {
                  name
                  description
                  type
                }
              }
            }
          }
        `,
        variables: { id: 0 }
      })
      .subscribe(({ data: { element: { children } } }) => {
        console.log(children); // this is the wanted result
        return children; // <-- return the value here
      });
    
    console.log("save");
    console.log(saved);   // <-- should have children assigned to saved
    

    【讨论】:

    • 有趣的想法。我想这确实应该有效。但是,日志给了我“订阅 {_cleanup: ƒ, _observer: {…}, _queue: undefined, _state: "ready"}”。
    猜你喜欢
    • 2012-02-27
    • 2019-02-28
    • 1970-01-01
    • 2020-12-23
    • 2020-05-20
    • 2021-12-28
    • 2019-05-17
    • 2015-05-09
    • 1970-01-01
    相关资源
    最近更新 更多