【问题标题】:Why can't apollo get data in first request?为什么 apollo 在第一个请求中无法获取数据?
【发布时间】:2020-07-28 13:20:16
【问题描述】:

我正在使用道具来获取鸟类的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 repo。

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

【问题讨论】:

    标签: vue.js vuex apollo-client nativescript-vue vue-apollo


    【解决方案1】:

    问题是你的模板

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

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

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

    您可以在 vue 组件的数据挂钩中初始化属性

    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>
    

    【讨论】:

    • 非常感谢。我将定义初始默认值就可以了
    • @cemkaan 感谢您的编辑。我完全错过了nativescript-vue 标签?
    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多