当我获取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中。为什么会这样呢?
下面的图片是我想要完成的。
这张照片是现在给我的结果
答案 0 :(得分:1)
希望您不介意,但我检查了您的个人资料并注意到了Github中的文件。问题出在src/index.html
,您在第35行定义<script src="bundle.js"></script>
。
但是,当您运行Webpack时,它将构建并注入同一行(如dist/index.html
所示),从而导致重复的API调用。
解决方法是从/src/index.html
中删除第35行:)您将不再需要使用伪造的JS调用API。
答案 1 :(得分:0)
forEach
工作正常。如果您检查要为其运行console.log
的{{1}}变量的scope
,则发现该作用域包含重复的数据,因此{{1} }循环。
forEach