[英]Can't make a search based on input value using fetched data . Getting a filter error
尝试进行取决于输入值的查询。 我正在使用国家 rest 编程接口。 期望的产量是来自 API 的解析信息,该信息由把手标记模板化。 如果您澄清可以修复我的代码的能力,那将是理想的。 非常感谢你。
import markupAdd from "../templates/markup.hbs";
const divInfo = document.querySelector("#main-container");
const search_input = document.querySelector(".input-field");
let search_term = "";
let countries;
const fetchCountries = () => {
countries = fetch(
"https://restcountries.eu/rest/v2/all?fields=name;flag;capital;population;languages"
).then((res) => res.json());
};
const showCountries = () => {
divInfo.innerHTML = "";
fetchCountries();
countries
.filter((country) =>
country.name.toLowerCase().includes(search_term.toLowerCase())
)
.map((item) => markupAdd(item))
.join("");
divInfo.insertAdjacentHTML("beforeend", infoBlock);
};
search_input.addEventListener("input", (e) => {
search_term = e.target.value;
showCountries();
});
车把
<div id="country-container">
<p class="country">{{name}}</p>
<img src="{{flag}}" alt="{{name}}" width="600" height="400">
<div id="info-container">
<p class="capital">Capital: {{capital}}</p>
<p class="population">Population: {{population}} </p>
<ul class="langs">
{{#each languages}}
<li class="language">Languages: {{name}}</li>
{{/each}}
</ul>
</div>
</div>
目前,输入任何字母后,我收到这种错误
apiInfo.js?b765:22 Uncaught TypeError: countries.filter is not a function
at showCountries (apiInfo.js?b765:22)
at HTMLInputElement.eval (apiInfo.js?b765:28)
fetchCounries
function 没有返回任何东西,下面是解决问题的一种方法。
async
functionconst fetchCountries = async () => {
let countries = await fetch(
"https://restcountries.eu/rest/v2/all?fields=name;flag;capital;population;languages"
);
let country = await countries.json();
return country;
};
const showCountries = () => {
divInfo.innerHTML = "";
fetchCountries().then(countries =>{
countries
.filter((country) =>
country.name.toLowerCase().includes(search_term.toLowerCase())
)
.map((item) => markupAdd(item))
.join("");
divInfo.insertAdjacentHTML("beforeend", infoBlock);
}).catch(err => {
console.log(err)
})
};
异步 Function 也返回一个 promise 所以稍后你可以使用 then catch 块来处理这个
要在没有异步等待的情况下做到这一点并且做得更清楚,你可以做这样的事情
const fetchCountries = () => {
fetch(
"https://restcountries.eu/rest/v2/all?fields=name;flag;capital;population;languages"
)
.then((res) => res.json())
.then((data) => {
showCountries(data);
})
.catch((err) => {
console.log(err);
});
};
const showCountries = (countries) => {
divInfo.innerHTML = "";
countries
.filter((country) =>
country.name.toLowerCase().includes(search_term.toLowerCase())
)
.map((item) => markupAdd(item))
.join("");
divInfo.insertAdjacentHTML("beforeend", infoBlock);
};
像这样更改您的 function:
async function fetchCountries() {
response = await fetch ("https://restcountries.eu/rest/v2/all?fields=name;flag;capital;population;languages");
return await response.json();
};
在您调用 function 的地方,只需使用.then 即可获取数据。
fetchCountries().then().catch();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.