React.js可搜索输入框功能失效,咨询修复方法
React可搜索输入框修复方案
你的代码存在几个关键问题导致搜索功能失效,以下是修复点和完整代码:
问题分析与修复
- 未保存过滤结果:执行
filter后没有将结果存储,始终渲染原country_list数组,导致搜索无效果。需要将过滤后的结果赋值给变量,渲染该变量。 - useState初始值错误:
useState()的初始值为undefined,调用inputVal.toLowerCase()时会触发报错,需将初始值设为空字符串''。 - filter逻辑不严谨:
filter回调应返回布尔值,当前返回country虽能运行但不符合规范;同时需处理inputVal为undefined的初始状态,避免报错。 - 冗余空片段:列表渲染中的
<>属于冗余代码,直接使用带key的div即可。
修复后的完整代码
import React, { useState } from 'react'; import "./styles.css"; export default function App() { const country_list = [ "Argentina", "Australia", "Belgium", "Belize", "China", "Iceland", "India", "Indonesia", "Iran", "Poland", "Portugal", "Romania", "Russia", "Saudi Arabia", "South Africa", "South Korea", "Swaziland", "Sweden", "Switzerland" ]; // 初始值设为空字符串 const [inputVal, setInputVal] = useState(''); // 存储过滤后的结果 const filteredCountries = country_list.filter(country => { // 处理初始状态和空输入的情况 if (!inputVal) { return true; } // 返回布尔值判断是否匹配 return country.toLowerCase().includes(inputVal.toLowerCase()); }); return ( <div className="App"> <input type="text" onChange={event => setInputVal(event.target.value)} /> {/* 渲染过滤后的数组 */} {filteredCountries.map((val, index) => ( <div key={index}> {val} </div> ))} </div> ) }
内容的提问来源于stack exchange,提问作者Rohit Verma
相关产品推荐
相关产品推荐

