【问题标题】:Why am I getting two sets of data from one api call using Fetch?为什么我使用 Fetch 从一个 api 调用中获取两组数据?
【发布时间】:2019-04-10 06:21:08
【问题描述】:

当我获取 api json 数据时,我得到双倍的结果。使用.forEach() 方法,我将双重数据打印到我只需要一组的HTML 中。

这是我的 api 调用和循环

var url = 'https://api.myjson.com/bins/1geede';

fetch(url)
.then(response => response.json())
.then(data =>  {

const scope = data.data.messages;
        console.log(scope);

        //Looping through the user data

        scope.forEach((i) => {

            let user = i;

            if (user.username == "Mygel van Trabel") {

                user1( user.focused, user.message, getTimeStamp(user.timestamp), user.username);

            } else {

                user2( user.focused, user.message, getTimeStamp(user.timestamp), user.username);

            }



        });

}).catch( error => console.error(error));

User1 和 User2 是函数。以下是来自console.log(scope) 的结果:

VM  app.js:20 (4) [{…}, {…}, {…}, {…}]
app.js:20     (4) [{…}, {…}, {…}, {…}]

现在它正在将两个集合都打印到 DOM 中,而我只需要一个。为什么会这样?

下面的图片是我想要完成的。

这张照片是它现在给我的结果

【问题讨论】:

  • user1user2 函数是什么?没有它也可以正常工作:jsfiddle.net/bvsLueky
  • 我刚刚将它们添加到帖子中
  • 看起来他们没有记录任何东西,但是没有它们,正如您从小提琴中看到的那样,数据不会重复(例如显示 4 个项目,而不是 8 个)。你能展示演示minimal reproducible example的代码吗?
  • @CertainPerformance 怎么样?
  • 您能否检查您的网络选项卡以确认该请求仅发送 1 次,并且 edit 您的帖子中包含此信息?这是重复记录最常见的情况

标签: javascript json api foreach


【解决方案1】:

希望您不介意,但我查看了您的个人资料并注意到您的 Github 中的文件。问题出在src/index.html,您在第 35 行定义了<script src="bundle.js"></script>

但是,当您运行 Webpack 时,它会构建和注入同一行(如 dist/index.html 中所示),从而导致您重复的 API 调用。

修复只是从 /src/index.html 中删除第 35 行 :) 您将不再让受骗的 JS 调用 API。

【讨论】:

    【解决方案2】:

    forEach 工作正常。如果您检查您正在为其运行 forEachscope 变量的 console.log,那么您会发现该范围包含重复的数据,因此您的 forEach 循环没有任何问题。

    fetch('https://api.myjson.com/bins/1geede')
    .then(response => response.json())
    .then(function(data) {
        //Declaring the scope variable for user data
        const scope = data.data.messages;
    
        console.log("Duplication is here: ", scope);
        console.log("---------");
    
        //Looping through the user data
        scope.forEach((i) => {
            let user = i;
    
            console.log(user);
        });
    });

    【讨论】:

    • 他的问题是他看到了 8 个结果,而不是 4 个。
    • @CertainPerformance 如果是这样的话,为什么我们没有看到他提供的代码的 8 个结果?
    • 因为 OP 没有提供minimal reproducible example。 (如果他的问题无法重现,最好要求澄清并投票关闭)
    猜你喜欢
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 2020-07-26
    • 2017-10-25
    相关资源
    最近更新 更多