React.js游戏搜索功能无法默认展示API全量列表问题
问题说明
开发支持多游戏检索的网站时,已完成基于游戏标题调用API的关键词匹配搜索逻辑,存在异常:搜索框未输入内容时,页面无法展示全量游戏列表。
预期效果:页面默认加载时始终展示API返回的全量游戏列表,用户输入搜索关键词后,页面自动过滤展示匹配关键词的游戏。
故障原因
- 列表过滤逻辑存在判断缺陷:原有过滤条件为
return searchTerm && title.startsWith(searchTerm),当搜索框为空时searchTerm是空字符串,属于JavaScript假值,判断结果恒为false,所有游戏项都会被过滤,因此空输入时无内容展示。 - 代码存在冗余问题:重复引入axios,且在组件渲染阶段直接执行了独立的接口请求逻辑,会导致组件每次重渲染都重复调用API,产生不必要的流量消耗和接口压力。
修复步骤
- 调整列表过滤规则:当搜索关键词为空时,直接返回全部游戏数据;存在有效关键词时再执行标题前缀匹配
- 移除重复的axios引入语句,删除组件渲染阶段直接执行的冗余接口请求,将接口请求逻辑收拢到仅在组件首次挂载时触发的
getGames方法中 - 额外增加搜索词首尾空格去除逻辑,避免用户误输入空格导致匹配失效
修复后完整代码
import React from "react"; import axios from "axios"; import { Link } from "react-router-dom"; const Games = () => { const [games, setGames] = React.useState([]); const [search, setsearch] = React.useState(""); const getGames = async () => { const options = { method: "GET", url: `https://free-to-play-games-database.p.rapidapi.com/api/games`, headers: { "X-RapidAPI-Key": "8145a0d66fmsh967b9729537d0f7p1aaab0jsncb9dccfb2e32", "X-RapidAPI-Host": "free-to-play-games-database.p.rapidapi.com", }, }; try { let response = await axios.request(options); console.log(response.data); setGames(response.data); } catch (error) { console.error(error); } }; React.useEffect(function () { getGames(); }, []); const searchGame = (event) => { setsearch(event.target.value); }; return ( <div className="main-games"> <input className="search" type="text" value={search} onChange={searchGame} placeholder="Enter game here..." /> {games .filter((item) => { const searchTerm = search.toLowerCase().trim(); const title = item.title.toLowerCase(); // 搜索词为空时返回全部游戏,否则匹配前缀 return searchTerm ? title.startsWith(searchTerm) : true; }) .map(function (game) { return ( <Link className="main-games-layout" key={game.id} to={`/games/${game.id}`} > <img src={game.thumbnail} alt="game picture" /> <br /> <h3>{game.title}</h3> <br /> {game.short_description} </Link> ); })} </div> ); }; export default Games;
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

