我从客户端向laravel API发送一个GET请求:
axios
.get(
config.apiUrl + "/api/news",
{
params: {
ids: ids
}
}
)
.then((response) => {
setNews([...news, ...response.data]);
})
.catch((error) => {
console.log(error);
return false;
})
ids
-可以为空的数组。
如果ids
为空,则在服务器端,控制器返回一个集合:
News::with('source:id,title,url')->orderByDesc('created_at')->limit(200)->get(
[
'created_at',
'custom',
'description',
'link',
'id',
'source_id',
'title'
]
);
这是我从服务器得到的响应:
在这种情况下,一切正常
如果ids
不为空,在服务器端,控制器返回其他集合:
News::with('source:id,title,url')->orderByDesc('created_at')->get(
[
'created_at',
'custom',
'description',
'link',
'id',
'source_id',
'title'
]
)->whereIn(
'id', $ids
);
这是我从服务器得到的响应:
在这种情况下,我得到错误“typeerrorresponse.datais not iterable”。
为什么会这样?怎么解决?
3条答案
按热度按时间fcg9iug31#
根据响应日志,当从Laravel发送API响应时,从Laravel发送的对象会自动转换为数组,当键为整数时,从0到n开始,不遗漏一个数字。这种索引机制与数组相同,因此,对象会转换为数组。
但是当索引是随机数而不是从0开始的直接索引时,键不能模仿数组的索引,因为这个原因,它仍然是一个对象。
前端的一个快速解决方案是 Package
response.data
以获得一个像Object.values(response.data)
这样的值数组,然后将它们设置在一个状态中。这将确保response.data
始终被分配为数组而不是对象。一个更好的方法是在laravel端修复它以返回数组。
bbmckpt72#
如你所见,response.data不是数组,而是一个对象。
{ 14304:{...},14305:我的天
你需要解决这个问题。在Larvel站点中,返回数据作为数组。
edqdpe6u3#
错误“TypeErrorresponse.datais not iterable”发生,因为当ids参数不为空时,Laravel控制器返回单个模型示例在JavaScript中,可以使用循环或类似map的方法来迭代数组或可迭代对象()、filter()、reduce()等,但不能直接迭代单个对象。
要解决此问题,您可以检查响应数据是单个对象还是数组,并相应地处理每种情况。例如:
在这段代码中,我们使用Array.isArray()方法来检查响应数据是否是数组。如果是数组,我们可以直接在setNews()方法中使用它。如果是单个对象,我们需要使用数组文字[ www.example.com ]将其 Package 在数组中response.data,以便我们可以迭代它。
通过这种修改,您的代码应该在id为空或不为空的两种情况下都能正常工作。