【问题标题】:Why does the data return undefined in a for loop even in a .then为什么即使在 .then 中,数据也会在 for 循环中返回 undefined
【发布时间】:2021-04-12 03:29:38
【问题描述】:

目前正试图弄清楚为什么 dataset[i]["stationId"] 以未定义的形式返回。 我也尝试使用我设置的数据,但它也会返回 undefined。但是,如果我控制台记录类似 dataset[0]["stationId"] 的内容,我将能够取回一些东西,但不是在 for 循环中。我想要做的是重组我从通话中收到的数据。

提前感谢您的回答!

const [data, setData] = useState([]);
    let arr= []
    var i;

    useEffect(() => {
        const fetchEvents = () => {
                fetch(`http://${ip.trim()}:${port}/events/station`)
                .then(response => response.json())
                .then(json => {
                    setData(json);
                    console.log(data)
                })
                .then(dataset =>{
                    if(arr.length === 0){
                                arr[0] = {stationId : dataset[0]["stationId"], event_type: dataset[0]["event_type"], duration: [dataset[0]["duration"]]}
                    }

                    for(i=0; i<arr.length; i++){
                        for(i=0; i<dataset.length; i++){
                            // if station id is not the same 
                                if(arr[i]["stationId"] !== dataset[i]["stationId"]){
                                    arr.push(dataset[i])
                                }
                                else if(arr[i]["event_type"] === dataset[i]["event_type"]){
                                    arr[i]["duration"].push(dataset[i]["duration"])
                                }
                                else{
                                    arr[i]["event_type"] = dataset[i]["event_type"]
                                    arr[i]["duration"] = [dataset[i]["duration"]]
                                }

                        }
                    }

                    
                })
                .catch(
                    err => {
                        console.log(err);
                    }
                );
        };

        fetchEvents();

    }, []);

【问题讨论】:

  • 您在两个for 循环中都使用i,因此您在每个循环中添加两次i。这就是出错的原因。
  • Klassiek,很好发现!非常感谢

标签: javascript reactjs asynchronous fetch call


【解决方案1】:

如 cmets 中所述,您的两个 for 循环使用相同的计数器。每次通过内部 for 循环后,i 都会增加,然后在外部 for 循环中它会再次增加。在某些时候,i 会增加很多,dataset[i] 将是未定义的。

将内部 for 循环放在函数中可以解决这个问题,就像这样做:

for(i=0; i<arr.length; i++){
    arr[i] = check(dataset, arr[i]);
}

function check(dataset, arri){
    for(var i=0; i<dataset.length; i++){
        // if station id is not the same 
            if(arri["stationId"] !== dataset[i]["stationId"]){
                arri.push(dataset[i])
            }
            else if(arri["event_type"] === dataset[i]["event_type"]){
                arri["duration"].push(dataset[i]["duration"])
            }
            else{
                arri["event_type"] = dataset[i]["event_type"]
                arri["duration"] = [dataset[i]["duration"]]
            }

    }
    return arri
}

但是,还有另一个问题,push 方法。比如说arr[i]如下:

arr[i]  === {stationId : 1, event_type: "a_type", duration: [1,2,3]}

那么arr[i].push(dataset[i]) 将不起作用。 push 方法适用于 Arrays。你正试图在Object 上推送一些东西。 Objects 没有 push 方法...

【讨论】:

  • 感谢 Klassiek。在您发布第一条评论并修复所有问题后,我意识到一切都错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2018-08-13
  • 1970-01-01
  • 2012-01-14
  • 2021-04-05
  • 1970-01-01
相关资源
最近更新 更多