gpt4 book ai didi

vue.js - 为什么 apollo 不能在第一个请求中获取数据?

转载 作者:行者123 更新时间:2023-12-04 10:13:05 25 4
gpt4 key购买 nike

我正在使用 Prop 来获取鸟类的 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>

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

我创建了一个显示问题的 repo 。请在这里检查:
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

最佳答案

问题是你的模板

<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>

关于vue.js - 为什么 apollo 不能在第一个请求中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61230982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com