我有这个api,它返回值的数组:
app.get("/events", (req, res) => {
let response = null;
let authObj = auth.authorize();
setTimeout(() => {
let result = controller.listEvents(authObj);
result.then((data) => {
response = data;
console.log(data)
res.json(response); // is this way of passing this data object to front-end right ???
});
}, 2000);
});
上面console.log(data)
的结果如下:
[
{
kind: 'calendar#event',
etag: '"3203302285276000"',
id: '69jte9qmoij84irjf2ktlqlqcd',
status: 'confirmed',
htmlLink: 'https://www.google.com/calendar/event?eid=NjlqdGU5cW1vaWo4NGlyamYya3RscWxxY2QgYmFudWthamFuYW5hdGhqYXlhcmF0aG5hQG0',
created: '2020-10-02T15:05:42.000Z',
updated: '2020-10-02T15:05:42.638Z',
summary: 'What’s New in Lens 3.6.0',
},
{
kind: 'calendar#event',
etag: '"3200206562152000"',
id: '_6l6jehjbbtol8him9194uqr88907cjaoct3japrle5a3ii9o6ds62t3kcln68pb5',
status: 'confirmed',
htmlLink: 'https://www.google.com/calendar/event?eid=XzZsNmplaGpiYnRvbDhoaW05MTk0dXFyODg5MDdjamFvY3QzamFwcmxlNWEzaWk5bzZkczYydDNrY2xuNjhwYjUgYmFudWthamFuYW5hdGhqYXlhcmF0aG5hQG0',
created: '2020-09-14T17:07:55.000Z',
updated: '2020-09-14T17:08:01.076Z',
summary: 'Ansible Contributor Summit - New Contributor Workshops',
}
]
我想将此data
传递到我的前端并对其进行迭代以显示summary
,status
。
这是我如何将此值传递到前端的方法:
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then((res) => {
console.log(res);
setData(res.data);
});
});
但是当我尝试打印data
时,它会显示undefined
有人可以帮我吗?
谢谢!
答案 0 :(得分:3)
该参数是响应。它不是请求的结果,它仅包含标头。您需要
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then(res => res.json()).then((res) => {
console.log(res);
setData(res);
});
}, []);
记住空的依赖项数组。您不想每次组件渲染时都只获取一次。
结果没有data属性,它只是一个数组。因此,请使用setData(res);
,而不要使用setData(res.data);
答案 1 :(得分:1)
试一下,因为您期待json
const [data, setData] = useState([]);
useEffect(() => {
fetch("/events").then((res) => {
return res.json()
}).then((responseJson) => {
console.log(responseJson);
});
});