laravel 在ReactJS项目中处理类似响应时出现“对象不可迭代”错误

ykejflvf  于 2023-04-13  发布在  React
关注(0)|答案(3)|浏览(179)

我从客户端向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”。
为什么会这样?怎么解决?

fcg9iug3

fcg9iug31#

根据响应日志,当从Laravel发送API响应时,从Laravel发送的对象会自动转换为数组,当键为整数时,从0到n开始,不遗漏一个数字。这种索引机制与数组相同,因此,对象会转换为数组。
但是当索引是随机数而不是从0开始的直接索引时,键不能模仿数组的索引,因为这个原因,它仍然是一个对象。
前端的一个快速解决方案是 Package response.data以获得一个像Object.values(response.data)这样的值数组,然后将它们设置在一个状态中。这将确保response.data始终被分配为数组而不是对象。
一个更好的方法是在laravel端修复它以返回数组。

bbmckpt7

bbmckpt72#

如你所见,response.data不是数组,而是一个对象。
{ 14304:{...},14305:我的天
你需要解决这个问题。在Larvel站点中,返回数据作为数组。

edqdpe6u

edqdpe6u3#

错误“TypeErrorresponse.datais not iterable”发生,因为当ids参数不为空时,Laravel控制器返回单个模型示例在JavaScript中,可以使用循环或类似map的方法来迭代数组或可迭代对象()、filter()、reduce()等,但不能直接迭代单个对象。
要解决此问题,您可以检查响应数据是单个对象还是数组,并相应地处理每种情况。例如:

axios
  .get(config.apiUrl + "/api/news", {
    params: {
      ids: ids,
    },
  })
  .then((response) => {
    // Check if the response data is an array or a single object
    const responseData = Array.isArray(response.data)
      ? response.data // If it's an array, use it directly
      : [response.data]; // If it's a single object, wrap it in an array

    setNews([...news, ...responseData]);
  })
  .catch((error) => {
    console.log(error);
    return false;
  });

在这段代码中,我们使用Array.isArray()方法来检查响应数据是否是数组。如果是数组,我们可以直接在setNews()方法中使用它。如果是单个对象,我们需要使用数组文字[ www.example.com ]将其 Package 在数组中response.data,以便我们可以迭代它。
通过这种修改,您的代码应该在id为空或不为空的两种情况下都能正常工作。

相关问题