我刚开始反应,我正在查询GRAPHQL端点并向它发送一个json对象。我有一个名为Service.jsx的文件,其中包含一个包含查询并返回promise的函数组件。该函数在List.jsx中呈现,我想在那里返回从查询中获得的"id"的值。我需要在返回块中放入什么才能获得id?感谢
我尝试了incident.count来获取项目数量,但无法获得值
list.jsx
import React, { useEffect, useState } from 'react'
import IncidentService from "services/Service.jsx";
const App = () => {
const [incidents, setIncidents] = useState([]);
useEffect(() => {
var incidentService = IncidentService();
incidentService.getIncidents()
.then(result => {
console.log(result.data.incidentsTop20);
setIncidents(result.data.incidentsTop20);
})
}, [true])
return <>
<h1>Count: {incidents.count}</h1>
/* code to return id should go here */
</>
}
export default App;
service.jsx
import React from 'react'
const IncidentService = () => {
var getIncidents = async () => {
const query = {
"query": `
{
incidentsTop20 {
id
}
}`
}
const url = "https://localhost:44344/graphql";
const opts = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(query)
};
var result = await fetch(url, opts)
var data = await result.json()
return data;
}
return {
getIncidents: getIncidents
}
}
export default IncidentService;
我需要在返回块中放入什么才能获得id?
给定incidents
是incident
的列表,只需使用map()
来迭代每个事件。id。
const getTimes = (incident) => (incident.map(i => (<span>i.time</span>)))
return (
<>
<h1>Count: {incidents.length}</h1>
{incidents.map(incident => (
<span>{incident.id}</span>
{getTimes(incident.incident)}
)}
</>
)