试图返回类似于映射的对象



我正试图返回一个对象列表,以便稍后在ag网格中显示。然而,我最初试图映射,但注意到它不是一个数组,它只包含在{}中,因此得到了nota函数错误。任何提示或相关资源的链接都将不胜感激,因为我还没有找到任何有助于我的东西

api返回{"author":"j.k rowling"、"title":"Harry Potter"、"id":"1"、"pages":"1000"}

useEffect(() => {
fetch(http://fakeapi.com/)
.then(res => res.json())
.then(json => json.map(res => {
return {
author: res.author,
title: res.title,
id: res.id,
pages: res.pages,
};
})
).then(res => setRowData(res));
}, []);

您从服务器得到的响应显示您得到的不是一个数组,而是一个艺术家。你需要让你的服务器返回一组图书信息。所以您的JSON响应是:

[
{
"id":"1",
"author": "j.k rowling",
"title": "Harry Potter",
"pages":"7000"
},
{
"id":"2",
"author": "a.k sayomh",
"title": "Singer role",
"pages":"10000"
},
//...
]

然后,在您的ag网格中,您可以像以前一样使用.map函数。

如果你没有得到一系列书籍信息,那么API就不适合你的用例。

假设API在总数据量为1的情况下返回一个对象,如果更多,则返回一个数组。然后你能做什么。

useEffect(() => {
fetch(http://fakeapi.com/)
.then(res => res.json())
.then(json => Array.isArray(json)
? json.map(res => ({
author: res.author,
title: res.title,
id: res.id,
pages: res.pages,
))
: [json]
).then(res => setRowData(res));
}, []);

最新更新