【发布时间】:2020-07-28 23:50:53
【问题描述】:
我正在尝试构建一个搜索功能来显示与 searchTerm 匹配的项目。我得到的数据来自一个 API,我想过滤掉除了 searchedTerm 项目之外的所有项目,初始 API 调用运行一次,使用 useEffect 和 [] 回调
const changeFilterItem = (values) => {
const data = [...item];
const index = data.indexOf(values);
if (index > -1) {
data.splice(index, 1);
} else {
data.push(values);
}
setItem([...data]);
};
useEffect(() => {
if (item !== null) {
setLoading(true);
let pokemonList = [];
async function fetchData() {
for (let i = 0; i < item.length; i++) {
let response = await getAllPokemonByType(initialURLType, item[i]);
const pokemons = [...response.pokemon, ...pokemonList];
pokemonList = pokemons.slice(0);
}
console.log(pokemonList);
await loadPokemonByFilter(pokemonList);
}
fetchData().then();
}
}, [item]);
const loadPokemonByFilter = async (data) => {
let _pokemonData = await Promise.all(
data.map(async (pokemon) => {
return await getPokemon(pokemon.pokemon);
})
);
setPokemonData(_pokemonData);
setLoading(false);
};
const renderSelected = (type) => {
if (item.indexOf(type) === -1) {
return "";
}
return classes.selected;
};
【问题讨论】:
-
如果我们能看到您当前的代码,这将是方式更容易提供帮助。过滤掉数据听起来像是在
Array上调用.filter()可以提供帮助,但我们不知道您从什么开始。 -
@Jacob 我已经添加了关于如何按宠物小精灵类型进行过滤的代码,但我想做同样的事情,但有一个搜索栏,不知道如何去做
标签: reactjs api filter use-state