React中如何根据选中的宝可梦类型返回对应筛选列表
宝可梦类型筛选实现方案
你这个场景用数组filter方法就能实现,比用reducer更直观简洁,不需要引入额外复杂逻辑。
首先先明确两个常见筛选场景,你可以按需选择:
- 场景1:只要宝可梦包含选中类型就返回(比如选草属性,草+毒属性的妙蛙种子也会被纳入结果)
- 场景2:仅返回仅属于选中类型的宝可梦(比如选草属性,只有单属性为草的宝可梦会被纳入,双属性的会被排除)
具体实现(修改List组件即可)
假设你的全量pokemons数组中,每个宝可梦对象的类型字段为types,是存储对应类型名称的数组,修改后的List组件代码如下:
import React from "react"; import { useLocation } from "react-router-dom"; import { pokemons } from "../data"; const List = () => { const { state: selectedType } = useLocation(); // 兜底处理:如果没有拿到选中的类型,返回空数组 const filteredPokemons = selectedType ? pokemons.filter(pokemon => { // 场景1写法:包含选中类型即可 return pokemon.types.includes(selectedType) // 如果需要场景2,把上面的return替换成下面这行即可 // return pokemon.types.length === 1 && pokemon.types[0] === selectedType }) : [] return ( <div> <h3>{selectedType ? `${selectedType}属性宝可梦列表` : '请先选择属性'}</h3> <ul> {filteredPokemons.map(pokemon => ( <li key={pokemon.name}>{pokemon.name}</li> ))} </ul> </div> ); }; export default List;
如果你确实想用reduce实现的话,写法如下:
const filteredPokemons = pokemons.reduce((result, currentPokemon) => { // 同样是场景1的判断条件,要场景2自行替换即可 if (currentPokemon.types.includes(selectedType)) { result.push(currentPokemon) } return result }, [])
两种写法效果完全一致,filter是专门为数组筛选设计的API,在这个场景下可读性更高。
内容的提问来源于stack exchange,提问作者Tainara
相关产品推荐
相关产品推荐

