javascript - React - 如何正确进行 API 调用并传递结果以进行进一步过滤?
问题描述
我为我的应用程序使用天气 API。这个想法是从 API 中获取一次作为数组的数据,然后将其传递给进一步处理。我的 App.js 文件如下所示:
import { useState, useEffect } from "react";
import Search from "./components/Search";
import axios from "axios";
function App() {
const [countries, setCountries] = useState([]);
useEffect(() => {
axios.get("https://restcountries.eu/rest/v2/all").then((response) => {
setCountries(response.data);
});
}, []);
return (
<div>
<Search countriesList={countries} />
</div>
);
}
export default App;
Search 组件包括一个文本输入字段,传入的数组将根据该字段进行过滤和动态显示。但是,不调用负责过滤的函数。以下是搜索组件的内容:
import { useState } from "react";
import Country from "./Country";
const Search = ({ countriesList }) => {
const [name, setName] = useState("");
console.log(countriesList);
console.log("countries received");
const filterCountries = (singleCountry, nameFilter) => {
console.log("hello");
console.log(singleCountry);
if (singleCountry.name.toLowerCase().includes(nameFilter.toLowerCase())) {
return singleCountry;
}
};
const countryRender = (showButtonCondition, showWeatherCondition) => {
return (
<div>
{countriesList
.filter((country) => filterCountries(country, name))
.map((filteredCountry) => (
<Country
key={filteredCountry.alpha3Code}
showButton={showButtonCondition}
showWeather={showWeatherCondition}
countryId={filteredCountry.alpha3Code}
countryName={filteredCountry.name}
countryCapital={filteredCountry.capital}
countryPopulation={filteredCountry.population}
countryLanguages={filteredCountry.languages}
countryFlag={filteredCountry.flag}
/>
))}
</div>
);
};
const nameChangeHandler = (event) => {
console.log(event.target.value);
setName(event.target.value);
};
return (
<div>
search: <input value={name} onChange={nameChangeHandler} />
<div>
{countriesList.length > 10 || countriesList.length === 0 ? (
<div>Too many countres, specify another filter</div>
) : (
<></>
)}
{countriesList.length === 1 ? countryRender(false, true) : <></>}
{countriesList.length > 1 && countriesList.length < 10 ? (
countryRender(true, false)
) : (
<></>
)}
</div>
</div>
);
};
export default Search;
我想问题是名称(用户输入)的变化状态导致整个搜索组件重新渲染并重新获得完整的数组,但是如何克服它呢?React.memo() 方法在这里似乎并不适用,因为文档明确指出它不应该用于防止组件重新渲染。
解决方案
你从来没有真正打电话countryRender(true, false)
。countriesList.length > 1 && countriesList.length < 10
它仅在其长度为 250时才被调用。
推荐阅读
- r - 为什么第二个 ifelse 没有在 R 中评估,为什么 if else 没有矢量化?
- html - 获取股票的动态数据
- docker - docker osxia LDAP 中的访问权限
- azure - 无法使用 Azure CLI 访问计费信息
- r - 如何将 keras 模型加载到 Rmarkdown 文件中并在 knitr 中进行预测?
- c# - 我如何在 asp.net 中显示 Dropbox 图像
- css - 嵌套的弹性项目没有被缩小。min-width:0 解决问题
- c# - C#:.NET HttpClient 超时太快
- python - 由于 EnvironmentError 无法安装软件包:[WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用
- javascript - 带有自定义 JS 文件的 Angular 应用程序在 localhost 和服务器上的运行方式不同