为什么 apollo 第一次请求获取不到数据?

Why can't apollo get data in first request?

我正在使用道具来获取鸟类的 Id。

当我第一次启动应用程序并点击进入第二页时,数据不会加载。 它给出以下错误;

JS: [Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"
JS:
JS: found in
JS:
JS: ---> <Detail> at components/Detail.vue
JS:        <Frame>
JS:          <Root>

但是在我第二次点击按钮后它会正确加载。


我创建了一个显示问题的存储库。请在这里检查: github repo

Working graphql playground

<template>
  <Page>
    <StackLayout>
      <Label :text="bird.name" textWrap="true" />
      <Button text="get data" @tap="getData" />
    </StackLayout>
  </Page>
</template>

<script>
import { gql } from "apollo-boost";

export default {
  props: ["birdID"],

  apollo: {
    bird: {
      query: gql`
        query($id: ID!) {
          bird(id: $id) {
            id
            name
          }
        }
      `,
      variables() {
        return {
          id: this.birdID,
        };
      },
    },
  },
  methods: {
    getData() {
      console.log("bird data: ", this.bird);
    },
  },
  mounted() {},
};
</script>

<style></style>

有没有更好的获取数据的方法?


回答正确

我已经用解决方案更新了 github 仓库。

https://github.com/kaanguru/query-data-from-prop

问题在于您的模板

<Label :text="bird.name" textWrap="true" />

尝试显示bird.name您的查询完成之前。

Vue Apollo documentation 通过定义一些初始默认值显示了一个简单的解决方法

You can initialize the property in your vue component's data hook

data: () => ({
  bird: {
    name: null
  }
}),

或者,利用 Loading state 功能有条件地呈现您的组件

<Label v-if="$apollo.loading" text="loading" textWrap="true" />
<StackLayout v-else>
  <Label :text="bird.name" textWrap="true" />
  <Button text="get data" @tap="getData" />
</StackLayout>