【发布时间】:2020-06-03 17:46:12
【问题描述】:
尝试在 react js 应用程序中使用 graphql API。不确定这种方法是否正确。
import React, { Component } from 'react'
import "./styles.css";
import axios from 'axios';
const appBaseUrl = axios.create({
baseURL: 'http://localhost:8099/graphql'
});
const tagslist = ` {
getTags
{
id
tagName
tagDesc
tagVersion
tagVersion
}
}
`;
class TagsController extends React.Component {
constructor(props) {
super(props);
this.state = { tags: []};
this.headers = [
{ key: "id", label: "Tag Id" },
{ key: "tagName", label: "Tag Name" },
{ key: "tagDesc", label: "Tag Description" },
{ key: "tagVersion", label: "Tag Version" }
];
}
componentDidMount() {
appBaseUrl
.post('', { query: tagslist })
.then(result =>
this.setState(() => ({
tags: result
})),
);
}
render() {
console.log("...... url builder ......")
const { tags } = this.state;
return (
<table border ="1">
<thead>
<tr>
{
this.headers.map(function(h) {
return (
<th key = {h.key}>{h.label}</th>
)
})
}
</tr>
</thead>
<tbody>
{tags &&
tags.data &&
tags.data.getTags.map(function(item, key) {
return (
<tr key={key}>
<td>{item.id}</td>
<td>{item.tagName}</td>
<td>{item.tagDesc}</td>
<td>{item.tagVersion}</td>
</tr>
);
})}
</tbody>
</table>
);
}
}
export default TagsController;
此处例外。
× 未处理的拒绝(TypeError):无法读取未定义的属性“映射”
TagsController.render src/TagsController.js:59 56 | } 57 | </tr> 58 | </thead> 59 | <tbody> | ^ 60 | {tags && 61 | tags.data && 62 | tags.data.getTags.map(function(item, key) { View compiled ▶ 18 stack frames were collapsed. (anonymous function) src/TagsController.js:35 32 | 33 | componentDidMount() { 34 | appBaseUrl 35 | .post('', { query: tagslist }) | ^ 36 | .then(result => 37 | this.setState(() => ({ 38 | tags: result
来自 API 的异常响应如下。
{
"data": {
"getTags": [
{
"id": "ef718cce-1269-4fbd-827c-832f7824c025",
"tagName": "Veera6",
"tagDesc": "Test Tag6",
"tagVersion": 0
},
{
"id": "0cda5ae9-e287-4666-804a-03f25e642d1f",
"tagName": "Veera9",
"tagDesc": "Test Tag9",
"tagVersion": 0
},
{
"id": "31f8f042-dbc0-4dbf-ada8-b94c7e2d2a39",
"tagName": "Veera8",
"tagDesc": "Test Tag8",
"tagVersion": 0
},
{
"id": "6292054c-8bfc-4d2d-b2f8-92e2bac5a578",
"tagName": "Veera7",
"tagDesc": "Test Tag7",
"tagVersion": 0
},
{
"id": "c6756e5c-8fa5-40a9-ab92-5242bda97de3",
"tagName": "Veera10",
"tagDesc": "Test Tag10",
"tagVersion": 0
}
]
}
}
基本上,我正在尝试使用 graphql 查询 API 并使用 react js 应用程序显示结果列表,但出现上述错误。看起来我在使用 graphql api 并构造 graphql 查询参数时遗漏了一些东西
任何帮助都非常感谢。
【问题讨论】:
标签: javascript reactjs react-native react-router graphql