You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript动态添加Div顺序问题求助:FreeCodeCamp Twitch TV API项目

Fixing Fixed Order for Twitch TV API Divs

Hey there! I totally get your frustration—nothing's more annoying than having your layout shift randomly every time you refresh. Let's break down why this is happening and how to fix it.

Why the Order Changes

The problem almost certainly comes from how you're handling the API requests. When you fetch data for each Twitch streamer, those are asynchronous calls—meaning the browser doesn't wait for one to finish before starting the next. So the responses can come back in any order, depending on how fast each request is processed by Twitch's servers. If you're appending each div as soon as you get a response, that's why the order changes every time.

Step-by-Step Solution

We need to first collect all the data, then render everything in the fixed order you want (based on your original list of streamer names). Here's how to do it:

  1. Define your fixed streamer list
    This will be our source of truth for the display order:

    const streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp"]; // Add your full list here
    
  2. Create fetch promises for each streamer
    We'll attach the streamer's username to the fetched data so we can match it later:

    const fetchPromises = streamers.map(streamer => 
      fetch(`https://api.twitch.tv/kraken/streams/${streamer}`)
        .then(response => response.json())
        .then(data => ({ ...data, username: streamer })) // Link data to the streamer name
    );
    
  3. Wait for all requests to complete, then sort and render
    Use Promise.all to wait for every API call to finish, then sort the results to match your original list before creating divs:

    Promise.all(fetchPromises)
      .then(allData => {
        // Sort fetched data to match our original streamer order
        const sortedData = streamers.map(streamer => 
          allData.find(entry => entry.username === streamer)
        );
        
        // Render each div in the sorted order
        sortedData.forEach(entry => {
          const streamDiv = document.createElement('div');
          // Add your custom content here (name, status, logo, etc.)
          streamDiv.innerHTML = `
            <h4>${entry.username}</h4>
            <p>${entry.stream ? "Live now!" : "Offline"}</p>
          `;
          // Append to your container element
          document.getElementById('stream-container').appendChild(streamDiv);
        });
      })
      .catch(err => console.error('Error fetching stream data:', err));
    

Key Takeaway

By collecting all data first and then sorting it against your original streamer list, you guarantee that the divs will always render in the order you want—no matter the order the API responses come in.

If you were previously appending divs inside each fetch's .then() block, replacing that with this method should resolve the order issue right away. Feel free to adjust the code to fit your existing project structure!

内容的提问来源于stack exchange,提问作者iffitheking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:20:39