[英]How to use fetched data for argument in a method
我正在嘗試制作一個從 SWAPI 獲取所有 pl.net 的應用程序,然后將它們顯示為頁面上的框。 我有_load()方法,它獲取數據,以及_render()方法,它應該渲染框。 _render()具有名稱、地形、人口參數。
這是我的代碼的一部分:
const box = document.createElement("div");
box.classList.add("box");
box.innerHTML = this._render({
name: '',
terrain: "placeholder",
population: 0,
});
document.body.querySelector(".main").appendChild(box);
this.emit(Application.events.READY);
}
_load()我在其中獲取數據
async function getPl.nets() { const urls = Array.from({ length: 7 }, (v, i) => `https://swapi.boom.dev/api/pl.nets?page=${i + 1}`); const promises = urls.map(url => fetch(url).then(res => res.json()).then(data => data.results)); const pl.netData = (await Promise.all(promises)).flat(); console.log(`Results for ${pl.netData.length} pl.nets downloaded...`); console.log('Results:', pl.netData); } getPl.nets()
_render({ name, terrain, population }) { return ` <article class="media"> <div class="media-left"> <figure class="image is-64x64"> <img src="${image}" alt="pl.net"> </figure> </div> <div class="media-content"> <div class="content"> <h4>${name}</h4> <p> <span class="tag">${terrain}</span> <span class="tag">${population}</span> <br> </p> </div> </div> </article> `; }
我需要做的是從獲取的數據中獲取這些參數的值。
Pastebin - https://pastebin.com/hbxfHC1U
根據您的 pastebin 片段,我做了一些調整。
首先修改您的_load
function 以便它返回 SWAPI 請求的結果。 我已經刪除了您在其中定義的 function,因為它看起來並不重要,而且您已經在async
上下文中。
在constructor
中使用_load
的返回值並將其傳遞給_create
。 (無論如何,您的評論表明這是您的意圖)。 在_create
循環數據中,創建您的框並通過傳遞每個項目所需的屬性來調用_render
方法。
class Application { constructor() { this._startLoading() this._load().then(data => this._create(data)).then(() => this._stopLoading()) } async _load() { const urls = Array.from({ length: 7 }, (v, i) => `https://swapi.boom.dev/api/pl.nets?page=${i + 1}`); const promises = urls.map(url => fetch(url).then(res => res.json()).then(data => data.results)); const pl.netData = await Promise.all(promises) return pl.netData.flat(); } //here should be moved the rendering of the boxes, I suppose by establishing a connection with _render() _create(data) { data.forEach(({ name, terrain, population }) => { const box = document.createElement("div"); box.classList.add("box"); box.innerHTML = this._render({ name, terrain, population, }); document.body.querySelector(".main").appendChild(box); }) } _render({ name, terrain, population, image = '' }) { return ` <article class="media"> <div class="media-left"> <figure class="image is-64x64"> <img src="${image}" alt="pl.net"> </figure> </div> <div class="media-content"> <div class="content"> <h4>${name}</h4> <p> <span class="tag">${terrain}</span> <span class="tag">${population}</span> <br> </p> </div> </div> </article> `; } // we can leave these two alone for now _startLoading() { console.log('loading'); } _stopLoading() { console.log('finished'); } } new Application();
<main class="main"></main>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.