首页 > 解决方案 > 努力从 Vanilla JavaScript 中的一对 API 中填充

问题描述

正在修改我正在学习的项目。最初的项目是创建一种无限滚动的 Twitter 克隆。帖子是从https://jsonplaceholder.typicode.com/ api 抓取的,我试图通过从另一个图像占位符 API 引入图像来添加另一个级别。我是一个菜鸟,所以我能够成功地从两个 API 中获取数据并填充 DOM。麻烦的是,在我目前的结构中,我正在重复占位符图像,因为我从占位符 api 中获取的内容位于 5 个对象块中。可以使用一些帮助来确保每个帖子都有不同的照片。谢谢,这里是新手。想知道我是否应该只填充一组对象并从那里工作,但也许我缺少一个快捷方式?

const postsContainer = document.getElementById("posts-container");
const loading = document.querySelector(".loader");
const filter = document.getElementById("filter");

let limit = 5;
let page = 1;

//Fetch Posts from API
async function getPosts() {
  const res = await fetch(
    `https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`
  );
  const data = await res.json();
  return data;
}

//Fetch Photos from another API
async function getPhoto(photo) {
  const res = await fetch(`https://randomuser.me/api`);
  const data = await res.json();
  photo = data.results[0].picture.thumbnail;
  return photo;
}

//Show items in DOM
async function showPosts() {
  const posts = await getPosts();
  const pic = await getPhoto();

  posts.forEach((post) => {
    const postEl = document.createElement("div");
    postEl.classList.add("post");
    postEl.innerHTML = `
        <div class="number">
          <img class="profile-pic" src="${pic}" alt="user photo" />
        </div>
        <div class="post-info">
          <h2 class="post-title">${post.title}</h2>
          <p class="post-body">
           ${post.body}
          </p>
        </div>
      </div>
      `;

    postsContainer.appendChild(postEl);
  });
}

//Show loader and fetch more posts

function showLoading() {
  loading.classList.add("show");

  setTimeout(() => {
    loading.classList.remove("show");
    setTimeout(() => {
      page++;
      showPosts();
    }, 1000);
  }, 300);
}

//Show initial posts

showPosts();

window.addEventListener("scroll", () => {
  const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

  if (scrollTop + clientHeight >= scrollHeight - 5) {
    showLoading();
  }
});

GitHub 回购:https://github.com/unsubstantiated-Script/infinite-scroller

TIA

标签: javascriptarraysapiobject

解决方案


问题解决了。需要在我的 forEach 循环中移动 pic 变量。那和异步 forEach 循环。


推荐阅读