无法读取 reactjs 应用程序中未定义的属性"forEach"



我有一个JS方法,该方法获取JSON文件并尝试从中获取信息:

getData(json) {
        var output = '';
        json.Legs.forEach(function (item) {
            .
            .
            .
            .
            .
            .
        });
        return output;
    }

我遇到此错误:

unturew typeError:无法阅读不确定的

的属性'

是否可以这样使用,还是我根本不应该使用foreach?有没有做到这一点的方法?

确认json.Legs不是null之后,您需要执行循环。例如

if(json.Legs){
  json.Legs.forEach(function (item) {
            .
            .
            .
            .
            .
            .
        });
}

将其添加为代码中的第一行,并查看其打印内容。如果是数组,则可以在其中所有forEach。否则会丢下正确的错误。

console.log(json.Legs)

类似的事情应该做到这一点(检查.legs属性是否存在,以及它是否在迭代前的数组(:

getData(json) {
    var output = '';
    if(json.Legs && Array.isArray(json.Legs)){
     json.Legs.forEach(function (item) {
        //do something with item
     });
    }
    return output;
}

最新更新